Description
Given integers n
and k
, find the lexicographically k-th smallest integer in the range from 1
to n
.
Note: 1 ≤ k ≤ n ≤ 109.
Example:
1 | Input: |
解法
思路是:对于每个点,有向右和像下两种走法,如果我们计算这个点一下的节点个数(不包含自己,但包含到这个点右边的节点的个数,在代码里为calstep的返回值),如果比剩余的步数少,则直接向右走,否则向下走。
计算这个点下的数目时,考虑是否为完整层,所以出现了calstep中与n的比较情况
参考思路:https://massivealgorithms.blogspot.com/2016/10/leetcode-440-k-th-smallest-in.html
具体代码如下:
1 | class Solution { |