丑数(LintCode)

丑数

设计一个算法,找出只含素因子357 的第 k大的数。

符合条件的数如:3,5,7,9,15......

样例

如果k=4, 返回 9

挑战

要求时间复杂度为O(nlogn)或者O(n)

 1 import java.util.Queue;
 2 import java.util.LinkedList;
 3 
 4 class Solution {
 5     /**
 6      * @param k: The number k.
 7      * @return: The kth prime number as description.
 8      */
 9     public long kthPrimeNumber(int k) {
10         long[] relust = new long[k];
11         relust[0] = 3;
12         relust[1] = 5;
13         relust[2] = 7;
14         int a = 0;
15         int b = 0;
16         int c = 0;
17 
18         for (int i=3;i<k ;i++ ) {
19             long temp = judge(relust[a]*3,relust[b]*5,relust[c]*7);
20             relust[i] = temp;
21             while(relust[a]*3 <= temp)a++;
22             while(relust[b]*5 <= temp)b++;
23             while(relust[c]*7 <= temp)c++;
24         }
25 
26         return relust[k-1];
27     }
28     public long judge(long a,long b,long c) {
29         long min = Math.min(a,b);
30         min = Math.min(min,c);
31         return min;
32     }
33 };
原文地址:https://www.cnblogs.com/FJH1994/p/5041846.html