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
.
Example:
Input: n = 10 Output: 12 Explanation:1, 2, 3, 4, 5, 6, 8, 9, 10, 12
is the sequence of the first10
ugly numbers.
Note:
1
is typically treated as an ugly number.n
does not exceed 1690.
Approach #1: C++. generate all ugly numbers then sort.
class Solution { public: int nthUglyNumber(int n) { vector<int> temp; for (long i = 1; i < INT_MAX; i = i*2) { for (long j = i; j < INT_MAX; j = j*3) { for (long k = j; k < INT_MAX; k = k*5) { temp.push_back(k); } } } sort(temp.begin(), temp.end()); return temp[n-1]; } };
Approach #2: Java. [order generate]
class Solution { public int nthUglyNumber(int n) { List<Integer> nums = new ArrayList<Integer>(); nums.add(1); int i1 = 0; int i2 = 0; int i3 = 0; while (nums.size() < n) { int ant = Math.min(nums.get(i1) * 2, Math.min(nums.get(i2) * 3, nums.get(i3) * 5)); nums.add(ant); if (nums.get(i1) * 2 == ant) i1++; if (nums.get(i2) * 3 == ant) i2++; if (nums.get(i3) * 5 == ant) i3++; } return nums.get(n-1); } }
Approach #3: Python.
class Solution(object): def nthUglyNumber(self, n): """ :type n: int :rtype: int """ ugly = [1] i2 = i3 = i5 = 0 while len(ugly) < n: while ugly[i2]*2 <= ugly[-1]: i2 += 1 while ugly[i3]*3 <= ugly[-1]: i3 += 1 while ugly[i5]*5 <= ugly[-1]: i5 += 1 ugly.append(min(ugly[i2]*2, ugly[i3]*3, ugly[i5]*5)) return ugly[-1]
永远渴望,大智若愚(stay hungry, stay foolish)