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 34 35 36
| class Solution { public int findKthNumber(int n, int k) { int nth = 1; int prefix = 1;
while (nth < k) { int nodeCount = getNodeCount(prefix, n); if (k > nth + nodeCount - 1) { prefix++; nth += nodeCount; } else { prefix *= 10; nth++; } }
return prefix; }
private int getNodeCount(int rootPrefix, int n) { int count = 0;
long endPrefix = rootPrefix + 1; long prefix = rootPrefix; while (prefix <= n) { count += Math.min(endPrefix, n + 1) - prefix; prefix *= 10; endPrefix *= 10; }
return count; } }
|
注意在计算节点数量过程中的数据越界问题,题目输入的数据最高为九次方。
References
440. K-th Smallest in Lexicographical Order