给定整数 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。
这个题我没有提交成功,但是本地IDE是正确的,原因是我用了static变量,我看了网上说由于leetcode是一次性执行全部,static变量就不起作用了。因为我在写先序遍历用的是递归然后就用了static变量记录第K个元素了,只要把递归改为非递归就好,这样就可以在一个函数中获取到第K个值。
思路:建立一个十叉树,然后先序遍历它,会发现顺序和我们需要的顺序刚好一样。
下面是实现:
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Scanner;
/**
* Created by 96274 on 2018/12/29.
*/
//十叉树结构
class TenTree{
int val;
TenTree child[] = new TenTree[10];
public TenTree(int val){
this.val = val;
}
}
public class T440 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k= sc.nextInt();
int c = findKthNumber(n,k);
System.out.print(""+c);
}
//这是题目给的那个入口函数
public static int findKthNumber(int n, int k) {
TenTree root = create_TT(n);
XXBL_TT(root,0,k+1);
return a;
}
//创建十叉树,思路参见二叉树创建
//大概是把父存到队列里,取出父,然后每次创建左右孩子,再入队孩子,循环
public static TenTree create_TT(int n){
TenTree root = new TenTree(-1);
Queue<TenTree> queue = new ArrayDeque<>();
if(n>9){
for(int i = 1 ; i<= 9; i++){
root.child[i-1] = new TenTree(i);
queue.offer(root.child[i-1]);
}
for(int i = 10 ; i<= n; ){
TenTree p = queue.poll();
for(int j = 0 ; j< 10&& i<=n; j++,i++){
p.child[j] = new TenTree(i);
queue.offer(p.child[j]);
}
}
}else{
for(int i = 1 ; i<= n; i++){
root.child[i-1] = new TenTree(i);
queue.offer(root.child[i-1]);
}
}
return root;
}
//这里就是我使用的static变量了,一个用来结束先序遍历,一个记录K值
static int a = -1;
static boolean isOver = false;
//先序遍历十叉树
public static void XXBL_TT(TenTree root,int cur,int k){
// System.out.println("cur="+cur+",k="+k);
if(root == null || isOver)
return;
cur ++;
if(cur == k ){
a= root.val;
//System.out.println("第K是:"+root.val);
isOver = true;
return;
}
//System.out.print(" "+root.val);
for(int i = 0 ; i< 10; i++){
XXBL_TT(root.child[i],cur+i,k); //这里是个坑,注意cur+i
}
}
}