Leetcode: K-th Smallest in Lexicographical Order

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.

第二遍做法:参考https://discuss.leetcode.com/topic/64624/concise-easy-to-understand-java-5ms-solution-with-explaination

Actually this is a denary tree (each node has 10 children). Find the kth element is to do a k steps preorder traverse of the tree.

Initially, image you are at node 1 (variable: curr),
the goal is move (k - 1) steps to the target node x. (substract steps from k after moving)
when k is down to 0, curr will be finally at node x, there you get the result.

we don‘t really need to do a exact k steps preorder traverse of the denary tree, the idea is to calculate the steps between curr and curr + 1 (neighbor nodes in same level), in order to skip some unnecessary moves.

Main function
Firstly, calculate how many steps curr need to move to curr + 1.

  1. if the steps <= k, we know we can move to curr + 1, and narrow down k to k - steps.
  2. else if the steps > k, that means the curr + 1 is actually behind the target node x in the preorder path, we can‘t jump to curr + 1. What we have to do is to move forward only 1 step (curr * 10 is always next preorder node) and repeat the iteration.

calSteps function

    1. how to calculate the steps between curr and curr + 1?
      Here we come up a idea to calculate by level.
      Let n1 = curr, n2 = curr + 1.
      n2 is always the next right node beside n1‘s right most node (who shares the same ancestor "curr")
      (refer to the pic, 2 is right next to 1, 20 is right next to 19, 200 is right next to 199).
    2. so, if n2 <= n, what means n1‘s right most node exists, we can simply add the number of nodes from n1 to n2 to steps.
    3. else if n2 > n, what means n (the biggest node) is on the path between n1 to n2, add (n + 1 - n1) to steps.
    4. organize this flow to "steps += Math.min(n + 1, n2) - n1; n1 *= 10; n2 *= 10;"
 1 public class Solution {
 2     public int findKthNumber(int n, int k) {
 3         int curr = 1;
 4         k--;
 5         while (k > 0) {
 6             int steps = calc(n, curr, curr+1);
 7             if (k >= steps) {
 8                 k -= steps;
 9                 curr = curr + 1;
10             }
11             else {
12                 k -= 1;
13                 curr = curr * 10;
14             }
15         }
16         return curr;
17     }
18
19     public int calc(int n, long n1, long n2) {
20         int steps = 0;
21         while (n1 <= n) {
22             steps += Math.min(n+1, n2) - n1;
23             n1 *= 10;
24             n2 *= 10;
25         }
26         return steps;
27     }
28 }

下面是我自己的方法,参考Lexicographical Numbers这道题,对是对的,但是挨个访问,没有skip, TLE了

 1 public class Solution {
 2     public int findKthNumber(int n, int k) {
 3         int cur = 1;
 4         for (int i=1; i<k; i++) {
 5             if (cur * 10 <= n) {
 6                 cur = cur * 10;
 7             }
 8             else {
 9                 while (cur>10 && cur%10==9) {
10                     cur /= 10;
11                 }
12                 cur  = cur + 1;
13             }
14         }
15         return cur;
16     }
17 }
时间: 2024-10-08 10:29:36

Leetcode: K-th Smallest in Lexicographical Order的相关文章

[LeetCode] K-th Smallest in Lexicographical Order 字典顺序的第K小数字

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

good article————K’th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)

这是本人在研究leetcode中Median of Two Sorted Arrays一题目的时候看到一篇文章,觉得非常好,其中对快速排序重新实现. 文章来源于http://www.geeksforgeeks.org/这个网站. We recommend to read following post as a prerequisite of this post. K'th Smallest/Largest Element in Unsorted Array | Set 1 Given an ar

[LeetCode] K sum(2Sum、3Sum、4Sum)

1 2Sum Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please not

[Leetcode]668.Kth Smallest Number in Multiplication Table

链接:LeetCode668 给定高度m?.宽度n 的一张?m * n的乘法表,以及正整数k,你需要返回表中第k?小的数字. 例?1: 输入: m = 3, n = 3, k = 5 输出: 3 解释: 乘法表: 1 2 3 2 4 6 3 6 9 第5小的数字是 3 (1, 2, 2, 3, 3). 相关标签:二分查找 乘法表的特点是每行和每列元素均按升序排序,这题就可以转换为[LeetCode]378.Kth Smallest Element in a Sorted Matrix.我们通过二

Leetcode 树 Binary Tree Zigzag Level Order Traversal

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie Binary Tree Zigzag Level Order Traversal Total Accepted: 8678 Total Submissions: 33047My Submissions Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from le

leetcode第一刷_Binary Tree Level Order Traversal II

很简单的题目,在想是不是后面就不要更这么简答的了,大家都会写,没人看啊.层序遍历的基础上,加了保存每一层,加了从下往上输出,就是一个vector和一个stack的问题嘛,无他,但手熟尔. class Solution { public: vector<vector<int> > levelOrderBottom(TreeNode *root) { vector<vector<int> > res; if(root == NULL) return res; q

【Leetcode】Kth Smallest Element in a Sorted Matrix

题目链接:https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/ 题目: Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix. Note that it is the kth smallest eleme

Leetcode 1030 Matrix Cells in Distance Order (排序)

Leetcode 1030 题目描述 We are given a matrix with R rows and C columns has cells with integer coordinates (r, c), where 0 <= r < R and 0 <= c < C. Additionally, we are given a cell in that matrix with coordinates (r0, c0). Return the coordinates o

leetcode 378. Kth Smallest Element in a Sorted Matrix

Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix. Note that it is the kth smallest element in the sorted order, not the kth distinct element. Example: matrix = [ [ 1, 5