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.
如果通过判断每个数是不是Ugly number,时间复杂度将很高。这里可以采用判断K内有多少个素数这个问题的解法,稍加变通。
首先1是ugly number,下个数是其*2,*3,*5的最小值。
用i2来代表是第几次*2,i3代表第几次*3,i5代表第几次*5。
抓住第n+1次*2比第n次*2大这个原理,*2后位置+1。
1 class Solution { 2 public: 3 int nthUglyNumber(int n) { 4 vector<int> uglys; 5 uglys.push_back(1); 6 int i2=0,i3=0,i5=0; 7 for(int i=1;i<n;i++) 8 { 9 int min_next = min(min(uglys[i2]*2,uglys[i3]*3),uglys[i5]*5); 10 uglys.push_back(min_next); 11 if(min_next==uglys[i2]*2) i2++; 12 if(min_next==uglys[i3]*3) i3++; 13 if(min_next==uglys[i5]*5) i5++; 14 } 15 return uglys[n-1]; 16 } 17 };