#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;}