Given integers n
k
and, find the lexicographically k-th smallest integer in the range from 1
to n
.
note:1≤k≤n≤109.
Example:
Input:n: k:2output:10explanation:the lexicographical order is [1, ten, One, A, 2, 3, 4, 5, 6, 7, 8, 9], so the Second smallest number is 10.
S
classSolution { Public: intFindkthnumber (intNintk) {intCur =1; --K; while(k >0) { Long LongStep =0, first = cur, last = cur +1; while(First <=N) {step+ = min ((Long Long) n +1, last)-First ; First*=Ten; Last*=Ten; } if(Step <=k) {++cur; K-=step; } Else{cur*=Ten; --K; } } returncur; }};
Similar topics:
Lexicographical Numbers
Resources:
Https://discuss.leetcode.com/topic/64624/concise-easy-to-understand-java-5ms-solution-with-explaination/2
https://discuss.leetcode.com/topic/64462/ C-python-0ms-o-log-n-2-time-o-1-space-super-easy-solution-with-detailed-explanations
Leetcode all in one topic summary (continuous update ...)
[Leetcode] k-th smallest in lexicographical order dictionary sequence k decimal number