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:
Input: n: 13 k: 2 Output: 10 Explanation: The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10.
s
class Solution { public: int findKthNumber(int n, int k) { int cur = 1; --k; while (k > 0) { long long step = 0, first = cur, last = cur + 1; while (first <= n) { step += min((long long)n + 1, last) - first; first *= 10; last *= 10; } if (step <= k) { ++cur; k -= step; } else { cur *= 10; --k; } } return cur; } };
类似题目:
参考资料:
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] K-th Smallest in Lexicographical Order 字典顺序的第K小数字
原文:http://www.cnblogs.com/grandyang/p/6031787.html