To prove safety offer-- number of ugly (c ++)

Description Title
contains only the number of prime factors 2, 3 and 5 is referred to ugly number (UglyNumber). For example 6,8 is the number of ugly, but not 14, because it contains quality factor 7, accustomed as we put 1 is the first ugly number. Seeking ascending through N ugly large number sequence.

Ideas:
1, is determined by one
individually determined for each integer number is not ugly. The definition of the ugly, ugly number only divisible by 2,3,5, that is, if a number divisible by 2, divided by 2 consecutive; if divisible by 3, divided by three consecutive; can be if 5 divisible, continuous divided by 5, if finally get one, then this number is the number of ugly, otherwise it is not.

2, create a number of ugly array has been found to save the
first approach is relatively inefficient, because the method for each number, whether or not the number of ugly scandal, have been calculated judgment, it's a waste to a certain extent.

According to the definition of the number of ugly, ugly numbers behind the results should be a multiple of the number of the previous ugly 2,3,5, so we can create an array, which number is the number of ugly row good sequence, each number is ugly front multiplied by the number 2,3,5 get ugly.

So how do you ensure sort it? Suppose the current array of ugly largest number of M, we have each multiplied by the number of ugly 2,3,5 (do not actually need the product number for each ugly, just to save time on every to position), respectively a first result after 2M greater than M 2 is multiplied by the first multiplied result M of greater than 3 3M, a first multiplied result M of greater than 5 3M, then the next ugly number is the smallest 2M, 3M, 5M's.

代码:
class Solution {
public:
int GetUglyNumber_Solution(int index) {
if(index <= 0)
return 0;
vector<int> nums(index);
nums[0] = 1;
int nextIndex = 1;
int index2 = 0, index3 = 0, index5 = 0;
while(nextIndex < index){
nums[nextIndex] = min(nums[index2]*2, min(nums[index3]*3, nums[index5]*5));
if(nums[index2]*2 <= nums[nextIndex]) ++index2;
if(nums[index3]*3 <= nums[nextIndex]) ++index3;
if(nums[index5]*5 <= nums[nextIndex]) ++index5;
++nextIndex;
}
return nums[index-1];
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

---------------------

Guess you like

Origin www.cnblogs.com/ly570/p/11109344.html
Recommended