華爲機試-明明的隨機數

#include<iostream>
#include<string>
using namespace std;

int main()
{
    int randomNumberCount;
    while(cin>>randomNumberCount)
    {
        int *p = new int[randomNumberCount]();
        for(int index = 0;index < randomNumberCount; index++)
        {
            cin >> *(p + index);
        }

        int temp;
        for(int index1 = 0; index1 < randomNumberCount; index1++)
        {
            for(int index2 = 0; index2 < randomNumberCount - index1 - 1; index2++)
            {
                if(*(p + index2) >= *(p + index2 + 1))
                {
                    temp = *(p + index2 + 1);
                    *(p + index2 + 1) = *(p + index2);
                    *(p + index2) = temp;
                }
            }
        }

        for(int index3 = 0;index3 < randomNumberCount;index3++)
        {
            if(*(p + index3) != *(p + index3 - 1))  
            {
                cout<<*(p + index3)<<endl;
            }           
        }
        delete[] p;
    }
    return 0;
}

在這裏有兩點需要特別注意:
1、因爲有多組測試用例,所以對於輸入必須要用while循環。
2、對於new出來的數組,賦值的時候注意個數要與開闢的空間的個數相同,要不然debug的時候會出現內存的泄漏(heap corruption detected: after normal block )。

當然在此我的方法,並不是最好的方法,有一位大神用了空間換取時間的方法,個人感覺思路非常好,大家可以借鑑下,代碼如下:

#include <iostream>
using namespace std;
int main() {
    int N, n;
    while (cin >> N) {
        int a[1001] = { 0 };
        while (N--) {
            cin >> n;
            a[n] = 1;
        }
        for (int i = 0; i < 1001; i++)
            if (a[i])
                cout << i << endl;
    }
    return 0;
}
發佈了58 篇原創文章 · 獲贊 46 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章