滴滴校招-尋找丑數(shù)-c++

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <map>
#include <string>
#include <vector>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <algorithm>
#include <unordered_map>
using namespace std;
/*解題思路:
* http://blog.csdn.net/coder_xia/article/details/6707600 */
int Min(int a, int b, int c)     
{     
    int temp = (a < b ? a : b);     
    return (temp < c ? temp : c);     
}     
int FindUgly(int n) //  
{     
    int* ugly = new int[n];     
    ugly[0] = 1;     
    int index2 = 0;     
    int index3 = 0;     
    int index5 = 0;     
    int index = 1;     
    while (index < n)     
    {     
        int val = Min(ugly[index2]*2, ugly[index3]*3, ugly[index5]*5); //競爭產(chǎn)生下一個丑數(shù)     
        if (val == ugly[index2]*2) //將產(chǎn)生這個丑數(shù)的index*向后挪一位;    
            ++index2;     
        if (val == ugly[index3]*3)   //這里不能用elseif,因為可能有兩個最小值,這時都要挪動;  
            ++index3;     
        if (val == ugly[index5]*5)     
            ++index5;     
        ugly[index++] = val;     
    }     

    int result = ugly[n-1];     
    delete[] ugly;     
    return result;     
}     
int main()     
{     
    int num;  
    cin >> num;  
    cout << FindUgly(num) << endl;  
    return 0;     
}  

面試題之丑數(shù)的C++實現(xiàn)求解(孤陋寡聞了,才知道丑數(shù)這么high的東東)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容