码迷,mamicode.com
首页 > 其他好文 > 详细

[LintCode] Kth Prime Number

时间:2015-01-14 18:08:01      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:interview

http://lintcode.com/en/problem/kth-prime-number/#

class Solution {
    /**
     * @param k: The number k.
     * @return: The kth prime number as description.
     */
    public long kthPrimeNumber(int k) {
        // write your code here
        
        Queue<Long> q3 = new LinkedList<>();
        q3.offer(3L);
        Queue<Long> q5 = new LinkedList<>();
        q5.offer(5L);
        Queue<Long> q7 = new LinkedList<>();
        q7.offer(7L);
        
        long v = 0;
        for (int i = 0 ; i < k ; i ++)
        {
            // Find min element from 3 tops.
            if (q3.peek() < q5.peek() && q3.peek() < q7.peek())
            {
                v = q3.poll();
                q3.offer(v * 3);
                q5.offer(v * 5);
                q7.offer(v * 7);
            }
            else if (q5.peek() < q3.peek() && q5.peek() < q7.peek())
            {
                v = q5.poll();
                q5.offer(v * 5);
                q7.offer(v * 7);
            }
            else
            {
                v = q7.poll();
                q7.offer(v * 7);
            }
        }
        return v;
    }
};


[LintCode] Kth Prime Number

标签:interview

原文地址:http://7371901.blog.51cto.com/7361901/1604021

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!