剑指offer 求第n个丑数
方法一:超時
class Solution {
public:
? ? int GetUglyNumber_Solution(int index) {
? ? ? ? if(index<=0)
? ? ? ? ? ? return 0;
? ? ? ? int num=0;
? ? ? ? int number=0;
? ? ? ? while(num!=index)
? ? ? ? {
? ? ? ? ? ? while(number%2==0)
? ? ? ? ? ? ? ? number/=2;
? ? ? ? ? ? while(number%3==0)
? ? ? ? ? ? ? ? number/=3;
? ? ? ? ? ? while(number%5==0)
? ? ? ? ? ? ? ? number/=5;
? ? ? ? ? ? if(number==1)
? ? ? ? ? ? ? ? num++;
? ? ? ? ? ? number++;
? ? ? ? }
? ? ? ? return number;
? ? }
};
方法二:
class Solution {
public:
? ? int GetUglyNumber_Solution(int index) {
? ? ? ? vector<int> result;
? ? ? ? result.push_back(1);
? ? ? ? int index2=0,index3=0,index5=0;
? ? ? ? int num = 1;
? ? ? ? while(num++<index){
? ? ? ? ? ? int num2 = result[index2]*2;
? ? ? ? ? ? int num3 = result[index3]*3;
? ? ? ? ? ? int num5 = result[index5]*5;
? ? ? ? ? ? int minValue = min(min(num2,num3),num5);
? ? ? ? ? ? result.push_back(minValue);
? ? ? ? ? ? if(minValue==num2)
? ? ? ? ? ? ? ? index2++;
? ? ? ? ? ? if(minValue==num3)
? ? ? ? ? ? ? ? index3++;
? ? ? ? ? ? if(minValue==num5)
? ? ? ? ? ? ? ? index5++;
? ? ? ? }
? ? ? ? return result[index-1];
? ? }
};
總結
以上是生活随笔為你收集整理的剑指offer 求第n个丑数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 剑指offer 从上到下打印二叉树
- 下一篇: 剑指offer-斐波那契数列