在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given integers 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. 给定整数 注意:1 ≤ k ≤ n ≤ 109。 示例 : 输入: 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 }
|
请发表评论