33、剑指offer--丑数
题目描述
把只包含因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
解题思路:本题定义三个指针,对于当前已排好序找到的最大的丑数M,记录恰乘2、乘3、乘5大于当前最大的丑数M的三个位置,然后求三个位置*2 *3 *5的最小值即为下一个丑数的值
1 class Solution 2 { 3 public: 4 int GetUglyNumber_Solution(int index) 5 { 6 if(index <=0 ) 7 return 0; 8 int *pUglyNumbers = new int[index]; 9 pUglyNumbers[0] = 1; 10 int newUglyIndex = 1; 11 12 //记录恰乘2、乘3、乘5大于当前最大的丑数M的三个位置 13 int *pMultiply2 = pUglyNumbers; 14 int *pMultiply3 = pUglyNumbers; 15 int *pMultiply5 = pUglyNumbers; 16 while(newUglyIndex < index) 17 { 18 int min = Min(*pMultiply2*2,*pMultiply3*3,*pMultiply5*5); 19 pUglyNumbers[newUglyIndex] = min; 20 while(*pMultiply2*2 <= pUglyNumbers[newUglyIndex]) 21 { 22 ++pMultiply2; 23 } 24 while(*pMultiply3*3 <= pUglyNumbers[newUglyIndex]) 25 { 26 ++pMultiply3; 27 } 28 while(*pMultiply5*5 <= pUglyNumbers[newUglyIndex]) 29 { 30 ++pMultiply5; 31 } 32 ++newUglyIndex; 33 } 34 int ugly = pUglyNumbers[newUglyIndex-1]; 35 delete[] pUglyNumbers; 36 return ugly; 37 } 38 int Min(int num1,int num2,int num3) 39 { 40 int min = (num1<num2)?num1:num2; 41 min = (min<num3)?min:num3; 42 return min; 43 } 44 };