华为机试-明明的随机数

#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值