Related: LeetCode 313 - Super Ugly Number
LIKE CODING: LeetCode [264] Ugly Number II
https://leetcode.com/discuss/52716/o-n-java-solution
https://discuss.leetcode.com/topic/22982/java-easy-understand-o-n-solution
This can be easily expanded if there are multiple primes.
https://leetcode.com/discuss/55304/java-easy-understand-o-n-solution
Compared with previous solution, this one computes each factor twice.
public class Solution { public int nthUglyNumber(int n) { if(n<=0) return 0; int a=0,b=0,c=0; List<Integer> table = new ArrayList<Integer>(); table.add(1); while(table.size()<n) { int next_val = Math.min(table.get(a)*2,Math.min(table.get(b)*3,table.get(c)*5)); table.add(next_val); if(table.get(a)*2==next_val) a++; if(table.get(b)*3==next_val) b++; if(table.get(c)*5==next_val) c++; } return table.get(table.size()-1); } }
https://leetcode.com/discuss/67392/my-java-o-n-implementation-and-explaination
public int nthUglyNumber(int n) { List<Integer> results = new ArrayList<>(); results.add(1); int idx2 = 0; int idx3 = 0; int idx5 = 0; int totalNums= 1; while(totalNums < n ){ int val2 = results.get(idx2) * 2; int val3 = results.get(idx3) * 3; int val5 = results.get(idx5) * 5; int thisPick; if(val2 <= val3 && val2 <= val5){ thisPick = val2; idx2++; } else if(val3 <= val2 && val3 <= val5){ thisPick = val3; idx3++; } else { // (val5 <= val2 && val5 <= val3) thisPick = val5; idx5++; } if(results.get(totalNums-1) != thisPick) { // is possible results.get(totalNums-1) == thisPick?
results.add(thisPick); totalNums++; } } return results.get(n - 1); }
http://shibaili.blogspot.com/2015/08/day-121-264-ugly-number-ii.html
Space Optimization:
Using 3 Queues:
https://leetcode.com/discuss/52710/java-solution-with-three-queues
public int nthUglyNumber(int n) { if (n < 1) return 0; Queue<Long> queue2 = new LinkedList<>(); Queue<Long> queue3 = new LinkedList<>(); Queue<Long> queue5 = new LinkedList<>(); queue2.add(1l); long val = 0; for (int i = 0; i < n; i++) { long v2 = queue2.isEmpty() ? Long.MAX_VALUE : queue2.peek(); long v3 = queue3.isEmpty() ? Long.MAX_VALUE : queue3.peek(); long v5 = queue5.isEmpty() ? Long.MAX_VALUE : queue5.peek(); val = Math.min(v2, Math.min(v3, v5)); if (val == v2) { queue2.poll(); queue2.add(val*2); queue3.add(val*3); } else if (val == v3) { queue3.poll(); queue3.add(val*3); } else queue5.poll(); queue5.add(val*5); } return (int)val; }
X. TreeSet
X. PriorityQueue
https://discuss.leetcode.com/topic/25088/java-solution-using-priorityqueue
Different way, but not efficient.
public int nthUglyNumber(int n) { if(n==1) return 1; PriorityQueue<Long> q = new PriorityQueue(); q.add(1l); for(long i=1; i<n; i++) { long tmp = q.poll(); while(!q.isEmpty() && q.peek()==tmp) tmp = q.poll(); q.add(tmp*2); q.add(tmp*3); q.add(tmp*5); } return q.poll().intValue(); }
Different https://leetcode.com/discuss/53615/java-solution-with-one-min-heap
http://fisherlei.blogspot.com/2015/10/leetcode-ugly-number-ii-solution.html
https://leetcode.com/discuss/53009/interesting-bounds-about-this-problem
http://shibaili.blogspot.com/2015/08/day-121-264-ugly-number-ii.html
http://www.cnblogs.com/grandyang/p/4741934.html
public boolean isUgly(int num) { if (num == 0) return false; if (num == 1) return true; while (num % 5 == 0) num /= 5; while (num % 3 == 0) num /= 3; while (num % 2 == 0) num /= 2; return num == 1; }
Read full article from LIKE CODING: LeetCode [264] Ugly Number II
LIKE CODING: LeetCode [264] Ugly Number II
Write a program to find the
n
-th ugly number.
Ugly numbers are positive numbers whose prime factors only include
2, 3, 5
. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12
is the sequence of the first 10
ugly numbers.
Note that
1
is typically treated as an ugly number.- The naive approach is to call
isUgly
for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones. - An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.
- The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3.
- Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).
int nthUglyNumber(int n) {
if
(n<1)
return
0;
deque<double> vec2, vec3, vec5;
vec2.push_back(1);
for
(int i=0; i<n; ++i){
double v2 = vec2.empty()?LLONG_MAX:vec2.front();
double v3 = vec3.empty()?LLONG_MAX:vec3.front();
double v5 = vec5.empty()?LLONG_MAX:vec5.front();
double v = min(v2, min(v3, v5));
if
(i==n-1)
return
v;
if
(v==v2){
vec2.pop_front();
vec2.push_back(v*2);
vec3.push_back(v*3);
vec5.push_back(v*5);
}
else
if
(v==v3){
vec3.pop_front();
vec3.push_back(v*3);
vec5.push_back(v*5);
}
else
{
vec5.pop_front();
vec5.push_back(v*5);
}
}
}
The ugly-number sequence is 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … because every number can only be divided by 2, 3, 5, one way to look at the sequence is to split the sequence to three groups as below:
(1) 1×2, 2×2, 3×2, 4×2, 5×2, …
(2) 1×3, 2×3, 3×3, 4×3, 5×3, …
(3) 1×5, 2×5, 3×5, 4×5, 5×5, …
We can find that every subsequence is the ugly-sequence itself (1, 2, 3, 4, 5, …) multiply 2, 3, 5.
Then we use similar merge method as merge sort, to get every ugly number from the three subsequence.
Every step we choose the smallest one, and move one step after,including nums with same value.
public int nthUglyNumber(int n) {
int[] ugly = new int[n];
ugly[0] = 1;
int index2 = 0, index3 = 0, index5 = 0;
int factor2 = 2, factor3 = 3, factor5 = 5;
for(int i=1;i<n;i++){
int min = Math.min(Math.min(factor2,factor3),factor5);
ugly[i] = min;
if(factor2 == min)
factor2 = 2*ugly[++index2];
if(factor3 == min)
factor3 = 3*ugly[++index3];
if(factor5 == min)
factor5 = 5*ugly[++index5];
}
return ugly[n-1];
}https://discuss.leetcode.com/topic/22982/java-easy-understand-o-n-solution
public int nthUglyNumber(int n) {
if(n<=0) return 0;
int a=0,b=0,c=0;
List<Integer> table = new ArrayList<Integer>();
table.add(1);
while(table.size()<n)
{
int next_val = Math.min(table.get(a)*2,Math.min(table.get(b)*3,table.get(c)*5));
table.add(next_val);
if(table.get(a)*2==next_val) a++;
if(table.get(b)*3==next_val) b++;
if(table.get(c)*5==next_val) c++;
}
return table.get(table.size()-1);
}
http://www.neozone.me/leetcode264.htmlThis can be easily expanded if there are multiple primes.
public
int
nthUglyNumber(
int
n) {
int
[] uglyNumber =
new
int
[n];
int
[] index =
new
int
[
3
];
// respectively for 2,3,5
int
[] factor = {
2
,
3
,
5
};
// respectively for 2,3,5
uglyNumber[
0
] =
1
;
for
(
int
i =
1
; i < n; i++){
int
min = Math.min(Math.min(factor[
0
], factor[
1
]), factor[
2
]);
uglyNumber[i] = min;
if
(min == factor[
0
]) factor[
0
] =
2
* uglyNumber[++index[
0
]];
if
(min == factor[
1
]) factor[
1
] =
3
* uglyNumber[++index[
1
]];
if
(min == factor[
2
]) factor[
2
] =
5
* uglyNumber[++index[
2
]];
}
return
uglyNumber[n -
1
];
}
Compared with previous solution, this one computes each factor twice.
public class Solution { public int nthUglyNumber(int n) { if(n<=0) return 0; int a=0,b=0,c=0; List<Integer> table = new ArrayList<Integer>(); table.add(1); while(table.size()<n) { int next_val = Math.min(table.get(a)*2,Math.min(table.get(b)*3,table.get(c)*5)); table.add(next_val); if(table.get(a)*2==next_val) a++; if(table.get(b)*3==next_val) b++; if(table.get(c)*5==next_val) c++; } return table.get(table.size()-1); } }
https://leetcode.com/discuss/67392/my-java-o-n-implementation-and-explaination
public int nthUglyNumber(int n) { List<Integer> results = new ArrayList<>(); results.add(1); int idx2 = 0; int idx3 = 0; int idx5 = 0; int totalNums= 1; while(totalNums < n ){ int val2 = results.get(idx2) * 2; int val3 = results.get(idx3) * 3; int val5 = results.get(idx5) * 5; int thisPick; if(val2 <= val3 && val2 <= val5){ thisPick = val2; idx2++; } else if(val3 <= val2 && val3 <= val5){ thisPick = val3; idx3++; } else { // (val5 <= val2 && val5 <= val3) thisPick = val5; idx5++; } if(results.get(totalNums-1) != thisPick) { // is possible results.get(totalNums-1) == thisPick?
results.add(thisPick); totalNums++; } } return results.get(n - 1); }
http://shibaili.blogspot.com/2015/08/day-121-264-ugly-number-ii.html
int
nthUglyNumber(
int
n) {
vector<
int
> ugly(n);
ugly[0] = 1;
int
p2 = 0, p3 = 0, p5 = 0;
for
(
int
i = 1; i < n; i++) {
int
nextUgly = min(ugly[p2] * 2,min(ugly[p3] * 3,ugly[p5] * 5));
if
(nextUgly == ugly[p2] * 2) {
p2++;
}
if
(nextUgly == ugly[p3] * 3) {
p3++;
}
if
(nextUgly == ugly[p5] * 5) {
p5++;
}
ugly[i] = nextUgly;
}
return
ugly[n - 1];
}
Using 3 Queues:
https://leetcode.com/discuss/52710/java-solution-with-three-queues
public int nthUglyNumber(int n) { if (n < 1) return 0; Queue<Long> queue2 = new LinkedList<>(); Queue<Long> queue3 = new LinkedList<>(); Queue<Long> queue5 = new LinkedList<>(); queue2.add(1l); long val = 0; for (int i = 0; i < n; i++) { long v2 = queue2.isEmpty() ? Long.MAX_VALUE : queue2.peek(); long v3 = queue3.isEmpty() ? Long.MAX_VALUE : queue3.peek(); long v5 = queue5.isEmpty() ? Long.MAX_VALUE : queue5.peek(); val = Math.min(v2, Math.min(v3, v5)); if (val == v2) { queue2.poll(); queue2.add(val*2); queue3.add(val*3); } else if (val == v3) { queue3.poll(); queue3.add(val*3); } else queue5.poll(); queue5.add(val*5); } return (int)val; }
X. TreeSet
I think to use TreeSet other than PriorityQueue is easier as you don't need to worry about duplicates. Time complexity is same.
public int nthUglyNumber(int n) {
TreeSet<Long> ans = new TreeSet<>();
ans.add(1L);
for (int i = 0; i < n - 1; ++i) {
long first = ans.pollFirst();
ans.add(first * 2);
ans.add(first * 3);
ans.add(first * 5);
}
return ans.first().intValue();
}
X. PriorityQueue
https://discuss.leetcode.com/topic/25088/java-solution-using-priorityqueue
Different way, but not efficient.
public int nthUglyNumber(int n) { if(n==1) return 1; PriorityQueue<Long> q = new PriorityQueue(); q.add(1l); for(long i=1; i<n; i++) { long tmp = q.poll(); while(!q.isEmpty() && q.peek()==tmp) tmp = q.poll(); q.add(tmp*2); q.add(tmp*3); q.add(tmp*5); } return q.poll().intValue(); }
Different https://leetcode.com/discuss/53615/java-solution-with-one-min-heap
http://fisherlei.blogspot.com/2015/10/leetcode-ugly-number-ii-solution.html
7: int nthUglyNumberGeneral(int n, vector<int>& factors) {
8: vector<int> uglys(1,1);
9: vector<int> indexes(factors.size(), 0);
10: while(uglys.size() < n) {
11: int min_v = INT_MAX;
12: int min_index = 0;
13: for(int k =0; k< factors.size(); k++) {
14: int temp = uglys[indexes[k]] * factors[k];
15: if(temp < min_v) {
16: min_v = temp;
17: min_index = k;
18: }
19: }
20: indexes[min_index]++;
21: // need to avoid duplicate ugly number
22: if(uglys[uglys.size()-1] != min_v) {
23: uglys.push_back(min_v);
24: }
25: }
26: return uglys[n-1];
27: }
从空间的优化来说,没有必要用一个uglys的数组保存所有的ugly number,尤其是当n是个非常大的数字。对于indexes指针扫过的ugly number,都可以丢掉了https://leetcode.com/discuss/53009/interesting-bounds-about-this-problem
- Actually, the input space is much smaller than expected if we insist an
int
range output. When inputn
is greater than1691
, the output overflows theint
range. - Another way to view this bound is that all ugly numbers must be in the form
2^a*3^b*5^c
. Since we havelog2(Integer.MAX_VALUE)=a<31
,log3(Integer.MAX_VALUE)=b<20
andlog5(Integer.MAX_VALUE)=c<14
, the combination allowed is surely under31*20*14~=8400
.
Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numbers whose prime factors only include
2, 3, 5
. For example, 6, 8
are ugly while 14
is not ugly since it includes another prime factor 7
.
bool isUgly(int num) {
if
(num==0)
return
false
;
if
(num==1)
return
true
;
for
(int i=2; i<6; ++i){
while
(num%i==0) num /=i;
}
return
num==1;
}
bool
isUgly(
int
num) {
if
(num == 1)
return
true
;
while
(
true
) {
int
t = num;
if
(num % 2 == 0) {
num /= 2;
}
if
(num % 3 == 0) {
num /= 3;
}
if
(num % 5 == 0) {
num /= 5;
}
if
(num == t)
return
false
;
if
(num == 1)
return
true
;
}
}
http://www.cnblogs.com/grandyang/p/4741934.html
bool isUgly(int num) { while (num >= 2) { if (num % 2 == 0) num /= 2; else if (num % 3 == 0) num /= 3; else if (num % 5 == 0) num /= 5; else return false; } return num == 1; }
bool isUgly(int num) { if (num <= 0) return false; while (num % 2 == 0) num /= 2; while (num % 3 == 0) num /= 3; while (num % 5 == 0) num /= 5; return num == 1; }https://leetcode.com/discuss/57435/simple-java-solution-for-ugly-number-problem
public boolean isUgly(int num) { if (num == 0) return false; if (num == 1) return true; while (num % 5 == 0) num /= 5; while (num % 3 == 0) num /= 3; while (num % 2 == 0) num /= 2; return num == 1; }
Design an algorithm to find the kth number such that the only prime factors are 3, 5, and 7. Note that 3, 5, and 7 do not have to be factors, but it should bot have any other prime factors. For example, the first several multiples would be (in order) 1, 3, 5, 7, 9, 15, 21
If we separated the list from the beginning by the constant factors, then we'd only need to check the first of
the multiples of 3, 5 and 7. All subsequent elements would be bigger.
public static int getKthMagicNumber(int k) {
if (k < 0) {
return 0;
}
int val = 0;
Queue<Integer> queue3 = new LinkedList<Integer>();
Queue<Integer> queue5 = new LinkedList<Integer>();
Queue<Integer> queue7 = new LinkedList<Integer>();
queue3.add(1);
for (int i = 0; i <= k; i++) { // Include 0th iteration through kth iteration
int v3 = queue3.size() > 0 ? queue3.peek() : Integer.MAX_VALUE;
int v5 = queue5.size() > 0 ? queue5.peek() : Integer.MAX_VALUE;
int v7 = queue7.size() > 0 ? queue7.peek() : Integer.MAX_VALUE;
val = Math.min(v3, Math.min(v5, v7));
if (val == v3) {
queue3.remove();
queue3.add(3 * val);
queue5.add(5 * val);
} else if (val == v5) {
queue5.remove();
queue5.add(5 * val);
} else if (val == v7) {
queue7.remove();
}
queue7.add(7 * val);
}
return val;
}
public static int removeMin(Queue<Integer> q) {
int min = q.peek();
for (Integer v : q) {
if (min > v) {
min = v;
}
}
while (q.contains(min)) {
q.remove(min);
}
return min;
}
public static void addProducts(Queue<Integer> q, int v) {
q.add(v * 3);
q.add(v * 5);
q.add(v * 7);
}
public static int getKthMagicNumber(int k) {
if (k < 0) {
return 0;
}
int val = 1;
Queue<Integer> q = new LinkedList<Integer>();
addProducts(q, 1);
for (int i = 0; i < k; i++) { // Start at 1 since we've already done one iteration
val = removeMin(q);
addProducts(q, val);
}
return val;
}
Brute Force
public static ArrayList<Integer> allPossibleKFactors(int k) {
ArrayList<Integer> values = new ArrayList<Integer>();
for (int a = 0; a <= k; a++) { // 3
int powA = (int) Math.pow(3, a);
for (int b = 0; b <= k; b++) { // 5
int powB = (int) Math.pow(5, b);
for (int c = 0; c <= k; c++) { // 7
int powC = (int) Math.pow(7, c);
int value = powA * powB * powC;
if (value < 0 || powA == Integer.MAX_VALUE || powB == Integer.MAX_VALUE || powC == Integer.MAX_VALUE) {
value = Integer.MAX_VALUE;
}
values.add(value);
}
}
}
return values;
}
public static int getKthMagicNumber(int k) {
ArrayList<Integer> possibilities = allPossibleKFactors(k);
Collections.sort(possibilities);
return possibilities.get(k);
}