小根堆+一个栈(可换成数组)

第k个数

http://www.nowcoder.com/questionTerminal/d5e776441a6e41ae9f9859413bdc1eca

三个小根堆。
每个堆中维护3/5/7的乘数。
代码较长。但重复代码很多。

import java.util.*;

public class KthNumber {
    public int findKth(int k) {
        // write code here
            PriorityQueue<Integer> queue3 = new PriorityQueue<>(new Comparator<Integer>() {
                @Override
                public int compare(Integer integer, Integer t1) {
                    return integer - t1;
                }
            });
            PriorityQueue<Integer> queue5 = new PriorityQueue<>(new Comparator<Integer>() {
                @Override
                public int compare(Integer integer, Integer t1) {
                    return integer - t1;
                }
            });
            PriorityQueue<Integer> queue7 = new PriorityQueue<>(new Comparator<Integer>() {
                @Override
                public int compare(Integer integer, Integer t1) {
                    return integer - t1;
                }
            });
            queue3.offer(3);
            queue5.offer(5);
            queue7.offer(7);
            Stack<Integer> stack = new Stack<>();
            stack.push(0);
            if(k == 0) return 0;
            int i = 0;
            while(i++<k){
                int temp = stack.peek();
                while (queue3.peek() <= temp) queue3.poll();
                while (queue5.peek() <= temp) queue5.poll();
                while (queue7.peek() <= temp) queue7.poll();
                int a = queue3.peek();
                int b = queue5.peek();
                int c = queue7.peek();
                int min = Math.min(a, Math.min(b,c));
                if(a == min){
                    int p = a * 3;
                    int q = a * 5;
                    int z = a * 7;
                    queue3.offer(p);
                    queue3.offer(q);
                    queue3.offer(z);
                    queue3.poll();
                }else if(b == min){
                    int p = b * 3;
                    int q = b * 5;
                    int z = b * 7;
                    queue5.offer(p);
                    queue5.offer(q);
                    queue5.offer(z);
                    queue5.poll();
                }else if(c == min){
                    int p = c * 3;
                    int q = c * 5;
                    int z = c * 7;
                    queue7.offer(p);
                    queue7.offer(q);
                    queue7.offer(z);
                    queue7.poll();
                }
                stack.push(min);
            }
            return stack.peek();
    }
}
全部评论

相关推荐

头像
11-09 17:30
门头沟学院 Java
TYUT太摆金星:我也是,好几个华为的社招找我了
点赞 评论 收藏
分享
尊尼获获:闺蜜在哪?
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务