Leetcode Note: uugly Number II
I. Description
Write a program to find the n-th uugly number.
Uugly 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 uugly numbers.
Note that 1 is typically treated as an uugly number.
Ii. Question Analysis
For the concept of Ugly Number, refer to uugly Number:
Numbers of ugliness starting from 1: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15 ,... The general idea of this question is to input a positive integer n and return the nth Ugly Number, which is more complicated than the uugly Number.
In fact, when observing these ugly arrays, it is nothing more than divided into the following three combinations (the first multiplier is the ugly number calculated last time, and the first ugly number is 1, the second multiplier is one of 2, 3, and 5 ):
(Take 2 as the multiplier) 1 × 2, 2 × 2, 3 × 2, 4 × 2, 5 × 2, 6 × 2, 8 × 2 ,... (Take 3 as the multiplier) 1 × 3, 2 × 3, 3 × 3, 4 × 3, 5 × 3, 6 × 3, 8 × 3 ,... (Take 5 as the multiplier) 1 × 5, 2 × 5, 3 × 5, 4 × 5, 5 × 5, 6 × 5, 8 × 5 ,...
Therefore, an array is opened to store n ugly numbers. During each iteration, the minimum ugly number of the product is selected from the three multiplication combinations and placed into the array. The last element of the final array is the ugly number.
Iii. Sample Code
Class Solution {public: int nthUglyNumber (int n) {int * uglyNum = new int [n]; // used to store the first n uglyNum [0] = 1; int factor2 = 2, factor3 = 3, factor5 = 5; int index2, index3, index5; index2 = index3 = index5 = 0; for (int I = 1; I <n; ++ I) {// obtain the minimum int minNum = min (factor2, factor3, factor5) in the three groups; uglyNum [I] = minNum; // Calculate if (factor2 = minNum) factor2 = 2 * uglyNum [++ index2] in three groups; if (factor3 = minNum) fa Ctor3 = 3 * uglyNum [++ index3]; if (factor5 = minNum) factor5 = 5 * uglyNum [++ index5];} int temp = uglyNum [n-1]; delete [] uglyNum; return temp;} private: // calculates the minimum int min (int a, int B, int c) of three numbers {int minNum = a> B? B: a; return minNum> c? C: minNum ;}};