★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-kjlrnbtf-ea.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given integers n
and k
, find the lexicographically k-th smallest integer in the range from 1
to n
.git
Note: 1 ≤ k ≤ n ≤ 109.github
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.
給定整數 n
和 k
,找到 1
到 n
中字典序第 k
小的數字。spa
注意:1 ≤ k ≤ n ≤ 109。code
示例 :htm
輸入: n: 13 k: 2 輸出: 10 解釋: 字典序的排列是 [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9],因此第二小的數字是 10。
8ms
1 class Solution { 2 func findKthNumber(_ n: Int, _ k: Int) -> Int { 3 var k = k 4 var cur:Int = 1 5 k -= 1 6 while (k > 0) 7 { 8 var step:Int = 0 9 var first:Int = cur 10 var last:Int = cur + 1 11 while (first <= n) 12 { 13 step += min(n + 1, last) - first 14 first *= 10 15 last *= 10 16 } 17 if step <= k 18 { 19 cur += 1 20 k -= step 21 } 22 else 23 { 24 cur *= 10 25 k -= 1 26 } 27 } 28 return cur 29 } 30 }