[leetcode 440]K-th Smallest in Lexicographical Order
来源:互联网 发布:淘宝爱逛街发布权限 编辑:程序博客网 时间:2024/05/21 10:55
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: 2Output:10Explanation: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,然后1-n按照字典排序,找出第k个数字
首先求(n,n+1)按照字典排序之间包含的数量sum
如果sum > k : n*=10 then k--
如果sum <= K:n++ then k-=sum
AC代码:
public class Solution { public static int findKthNumber(int n, int k) { int res = 1; --k; while(k > 0){ long sum = getSum(res, n); if(sum <= k){ k -=sum; ++res; }else{ res *= 10; --k; } } return res; } public static long getSum(long start,long n){ long end = start + 1; long sum = 0; while(start <= n){ sum += Math.max(0,(Math.min(n+1,end)-start)); start *=10; end *= 10; } return sum ; }}
更多leetcode题解:更多leetcode题解查看
0 0
- [leetcode]K-th Smallest in Lexicographical Order
- [leetcode 440]K-th Smallest in Lexicographical Order
- [LeetCode]440. K-th Smallest in Lexicographical Order
- [Leetcode] 440. K-th Smallest in Lexicographical Order 解题报告
- 440. K-th Smallest in Lexicographical Order
- 440. K-th Smallest in Lexicographical Order
- K-th Smallest in Lexicographical Order
- leetcode 440. K-th Smallest in Lexicographical Order 第k个字典序的数字
- Find k-th smallest element in BST (Order Statistics in BST)
- LeetCode Find K-th Smallest Pair Distance
- Find K-th smallest in N sorted arrays
- LeetCode Weekly Contest 56 Find K-th Smallest Pair Distance
- LEETCODE: 719 Find K-th Smallest Pair Distance
- leetcode 719. Find K-th Smallest Pair Distance
- Find the k-th smallest element
- 719. Find K-th Smallest Pair Distance
- good article————K’th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)
- Lexicographical order, dictionary order, permutation
- 【ECHARTS】 formatter回调函数
- 洛谷 1102 P1102 A-B数对
- PHP实现通过IP限制投票次数
- 16.淘宝的架构演化案例
- poj 1054 The Troublesome Frog
- [leetcode 440]K-th Smallest in Lexicographical Order
- AsyncTask的理解
- CI工作流程
- PHP统计当前在线人数
- 05-Jdbc获取数据库资源基本步骤
- 关于Java内存泄漏及如何检测
- PHP的几种加密解密算法
- Java多线程共享资源
- 读入带空格的字符串方法(小知识)