题目1431:Sort

来源:互联网 发布:mac应用商店 编辑:程序博客网 时间:2024/05/06 13:24

Hash算法

 #include<iostream>using namespace std;#define OFFSET 500000 int num[1000001]={0};//Hash数组 int main(){    int n;//n个不同数    int m;//输出m个最大数    int i;//控制输入    int j;//控制输出    int tmp;     while(cin >> n >>m)    {        //每次都要初始化这个大数组        for(i = -500000; i<=500000; i++)        {            num[i+OFFSET] =0;        }        //改变相应位置的值        for(i=0; i< n; i++)        {            cin >> tmp;            num[tmp+OFFSET] ++;        }          //从后往前输出m个数 遇到0跳过        j = 1000000;        while(0!=m)        {            if(num[j] !=0 )            {                if(1 !=m)                {                    cout << j-OFFSET <<" ";                }                else                {                    cout << j-OFFSET <<endl;                }                m--;            }            j--;        }    }    return 0;}/**************************************************************    Problem: 1431    User: itswyy    Language: C++    Result: Accepted    Time:800 ms    Memory:5424 kb****************************************************************/

用数组记录排序时间复杂度太高上千万,nlogn

#include<iostream>#include<algorithm>using namespace std; bool cmp(const int a, const int b){    return a >b;} int nums[1000000]; int main(){    int n;//n个不同数    int m;//输出m大数     int i,j;    while(cin >> n >> m && m>0 && n>0 && n>m)    {        for(i=0; i< n; i++)        {            cin >> nums[i];        }        sort(nums,nums+n,cmp);        for(j =0; j <m-1; j++)        {            cout << nums[j] << " ";        }        cout << nums[j] << endl;    }     return 0;}/**************************************************************    Problem: 1431    User: itswyy    Language: C++    Result: Accepted    Time:900 ms    Memory:5424 kb****************************************************************/

注意:犯了把i,j声明放在了for里,在for外调用了j 。导致Compile Error

0 0
原创粉丝点击