zoukankan      html  css  js  c++  java
  • [Swift]LeetCode440. 字典序的第K小数字 | K-th Smallest in Lexicographical Order

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
    ➤微信公众号:山青咏芝(shanqingyongzhi)
    ➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
    ➤GitHub地址:https://github.com/strengthen/LeetCode
    ➤原文地址:https://www.cnblogs.com/strengthen/p/10339102.html 
    ➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
    ➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

    Given integers n and k, find the lexicographically k-th smallest integer in the range from 1 to n.

    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.

    给定整数 n 和 k,找到 1 到 n 中字典序第 k 小的数字。

    注意: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 }
  • 相关阅读:
    数学考试
    奇♂妙拆分
    11.25
    11.21
    11.20
    11.19
    11.18
    11.15
    11.14作业
    11.14
  • 原文地址:https://www.cnblogs.com/strengthen/p/10339102.html
Copyright © 2011-2022 走看看