[LintCode]Ugly Number
Version 1 Memory Limit Exceeded 失败
class Solution {
/**
* @param k: The number k.
* @return: The kth prime number as description.
*/
public long kthPrimeNumber(int k) {
// Memory Limit Exceeded
ArrayList<Boolean> list = new ArrayList<Boolean>();
list.add(false); // 0
list.add(true); // 1
list.add(false); // 2
list.add(true); // 3
list.add(false); // 4
list.add(true); // 5
list.add(false); // 6
list.add(true); // 7
// 从8开始一个一个的找,下一个ugly number是第4个
int index = 3;
int num = 8;
while (true) {
if (num % 3 == 0 && list.get(num / 3)) {
list.add(true);
index++;
} else if (num % 5 == 0 && list.get(num / 5)) {
list.add(true);
index++;
} else if (num % 7 == 0 && list.get(num / 7)) {
list.add(true);
index++;
} else {
list.add(false);
}
if (index == k) {
return num;
}
num++;
}
}
};
Version 2 Time Limit Exceeded 失败
class Solution {
/**
* @param k: The number k.
* @return: The kth prime number as description.
*/
public long kthPrimeNumber(int k) {
// Time Limit Exceeded
HashSet<Integer> set = new HashSet<>();
set.add(3);
set.add(5);
set.add(7);
// 从8开始一个一个的找,下一个ugly number是第4个
int index = 3;
int num = 8;
while (true) {
if (num % 3 == 0 && set.contains(num / 3)) {
set.add(num);
index++;
} else if (num % 5 == 0 && set.contains(num / 5)) {
set.add(num);
index++;
} else if (num % 7 == 0 && set.contains(num / 7)) {
set.add(num);
index++;
}
if (index == k) {
return num;
}
num++;
}
}
};
class Solution {
/**
* @param k: The number k.
* @return: The kth prime number as description.
*/
public long kthPrimeNumber(int k) {
// 2016-03-14 不会计算时间复杂度
if (k <= 0) {
return 0;
}
long[] factors = {(long)3, (long)5, (long)7};
HashSet<Long> set = new HashSet<>(); // 防止反复插入同一个数
PriorityQueue<Long> queue = new PriorityQueue<>();
for (int i = 0; i < 3; i++) {
set.add(factors[i]);
queue.add(factors[i]);
}
// 循环k次,每次取出一个最小的ugly number
// queue中元素个数越来越多,效率越来越低
long minNum = 0;
long newNum = 0;
for (int i = 0; i < k; i++) {
minNum = queue.poll(); // 取出最小的ugly number
for (int j = 0; j < 3; j++) {
newNum = minNum * factors[j];
if (!set.contains(newNum)) {
set.add(newNum);
queue.add(newNum);
}
}
}
return minNum;
}
};