题目链接:https://leetcode.com/problems/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.
Hint:
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.class Solution { public: int nthUglyNumber(int n) { vector<int> uglyNum; uglyNum.push_back(1); int l2 = 0; int l3 = 0; int l5 = 0; int nextIndex = 1; while(nextIndex < n) { int value = min(uglyNum[l2]*2, min(uglyNum[l3]*3, uglyNum[l5]*5)); uglyNum.push_back(value); while(uglyNum[l2]*2 <= uglyNum[nextIndex]) l2++; while(uglyNum[l3]*3 <= uglyNum[nextIndex]) l3++; while(uglyNum[l5]*5 <= uglyNum[nextIndex]) l5++; nextIndex++; } return uglyNum[nextIndex - 1]; } };