尋找發帖“水王”的擴充問題

來源:互聯網
上載者:User
#include<stdio.h>#include<stdlib.h>/*  在一個論壇,發現有三個發帖很多的Id ,他們發帖的總數都超過了總數的1/4 ,編程快速的找到這三個id   演算法: 每次刪除是個不同的Id ,那麼最後剩下的 三個Id 就是所求的id */void findThreeK(int* p,int length){     int candidate[3],nTimes[3]={0,0,0},i;          for(i=0;i<length; i++)     {       if(p[i]==candidate[0])         {         nTimes[0]++;       }       else if(p[i]==candidate[1])       {         nTimes[1]++;       }       else if(p[i]==candidate[2])       {         nTimes[2]++;       }       else if(nTimes[0]==0)          {             candidate[0]=p[i];             nTimes[0] = 1;          }        else if(nTimes[1]==0)          {             candidate[1]=p[i];             nTimes[1] = 1;          }        else if(nTimes[2]==0)         {             candidate[2] = p[i];             nTimes[2] = 1;         }         else {                nTimes[0]--;                nTimes[1]--;                nTimes[2]--;              }     }   for(int i = 0 ; i < 3;i++)   printf("%d " ,candidate[i]);} int main(){    FILE *fread = fopen("Id.txt","r");        if(fread==NULL)    {       printf("can't open the file!\n");       exit(0);    }    int current = 0;    // 動態初始化數組 p ,如果不初始化會出現錯誤     int *p = (int*)malloc(sizeof(int)*10);           // id數組的長度     int length = 0 ;     // 將 資料讀入記憶體,存入數組P     while(fscanf(fread,"%d",¤t)!=EOF)    {       if(length%10==0)       p = (int*)realloc(p , sizeof(int)*(length+10));       p[length] = current;       length++;    }        findThreeK(p,length);    /*    for(int i = 0 ;i < length ;i++)    printf("%d ",p[i]);    */    system("pause");     return 0;} 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.