Leetcode: 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.

https://my.oschina.net/Tsybius2014/blog/495962的解释比较好懂
注意里面的三个if不能是else if否则会出现duplicate,例如2*3 和 3*2得到的是同一个ugly number。


public class Solution {
public int nthUglyNumber(int n) {
int[] uglyNumbers = new int[n];
uglyNumbers[0] = 1;
int index2 = 0, index3 = 0, index5 = 0;

for (int nthUglyNumber = 2; nthUglyNumber <= n; nthUglyNumber++) {
int uglyNumber = Math.min(uglyNumbers[index2]*2, Math.min(uglyNumbers[index3]*3, uglyNumbers[index5]*5));
if (uglyNumber == uglyNumbers[index2]*2) {
index2++;
}
if (uglyNumber == uglyNumbers[index3]*3) {
index3++;
}
if (uglyNumber == uglyNumbers[index5]*5) {
index5++;
}
uglyNumbers[nthUglyNumber-1] = uglyNumber;
}
return uglyNumbers[n-1];
}
}

Leave a comment