Problem
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.
Solution 1
最直接的方法,利用 ugly number I 的方法 isUgly( )。对从1开始的每个数字都调用 isUgly( ), 直到第n个数。
Time : O(nlgn) Space O(1)
Solution 2
稍微数学推导一下,一个数字如果想成为ugly number, 它只能是比它小的ugly number乘以2,3或者5才可以。
也就是说,从1开始,可以用三个指针 idx2, idx3 和 idx5分别指向当前分别乘以2,3,5后有可能成为下一个ugly number的数的位置,
相乘后三个中间最小的那个就是下一个ugly number,并将其index向后移一位。
bug : 如果分别乘以2,3,5后有数相等,那么相等的每个index 都要向后移动一位。
这里我就出错了, 应该是if 语句,我第一次都写成if else 了。
class Solution {
public:
int nthUglyNumber(int n) {
vector<int> nums(n, 1);
int idx2 = 0, idx3 = 0, idx5 = 0;
for( int i =1; i < n; i++){
int num2 = nums[idx2]*2, num3 = nums[idx3]*3, num5 = nums[idx5]*5;
int nextUglyNum = 0;
if(num2 <= num3 && num2 <= num5){
nextUglyNum = num2;
idx2++;
}
if( num3 <= num2 && num3 <= num5 ){
nextUglyNum = num3;
idx3++;
}
if( num5 <= num2 && num5 <= num3) {
nextUglyNum = num5;
idx5++;
}
nums[i] = nextUglyNum;
}
return nums[n-1];
}
};