来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/k-th-smallest-in-lexicographical-order
题目
给定整数 n
和 k
,返回 [1, n]
中字典序第 k
小的数字。
思路
同层从左到右字典序以此增大,字典序处于同层两个节点间的有$x$个,$x$取决于当前层高和节点总数$n$。如果$k$剩余大于等于两个节点间所有节点,则向右移动同时减去相应节点数,否则向下移动。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| class Solution { public: int count(long long n, long long cur) { long long next = cur+1; long nodes = 0; while(cur <= n) { nodes += min(n-cur+1, next-cur); cur *= 10; next *= 10; } return nodes; } int findKthNumber(int n, int k) { int cur = 1; --k; while(k) { int nodes = count(n,cur); if (k >= nodes) { k -= nodes; ++cur; } else { --k; cur *= 10; } } return cur; } } ;
|