寻找小水王
?
尋找發(fā)帖“水王”問(wèn)題的擴(kuò)展:“超級(jí)水王”沒(méi)有了。統(tǒng)計(jì)結(jié)果表明,有3個(gè)發(fā)帖很多的ID,他們的發(fā)帖數(shù)目都超過(guò)了帖子總數(shù)目N的1/4。你能從發(fā)帖ID列表中快速找出他們的ID嗎?
?
(一)分析問(wèn)題:
如果每次刪除四個(gè)不同的ID(不管是否包含發(fā)帖數(shù)目超過(guò)總數(shù)1/4的ID),那么,在剩下的ID列表中,原先發(fā)帖比例大于1/4的ID所占比例仍然大于1/4,可以通過(guò)不斷重復(fù)這個(gè)過(guò)程,把ID列表中的ID總數(shù)降低(轉(zhuǎn)化為更小的問(wèn)題),從而得到問(wèn)題的答案
(二)代碼實(shí)現(xiàn):
package 找小水王;public class Xiaoshuiwang {static void Find(int ID[],int N,int candidate[]){int nTimes[]={0,0,0};for(int i=0;i<N;i++){if(ID[i]==candidate[0]){nTimes[0]++;}else if(ID[i]==candidate[1]){nTimes[1]++;}else if(ID[i]==candidate[1]){nTimes[2]++;}else if(nTimes[0]==0){nTimes[0]=1;candidate[0]=ID[i];}else if(nTimes[1]==0){nTimes[1]=1;candidate[1]=ID[i];}else if(nTimes[2]==0){nTimes[2]=1;candidate[2]=ID[i];}else{nTimes[0]--;nTimes[1]--;nTimes[2]--;}}System.out.println("三個(gè)符合條件的ID分別是");for(int i=0;i<3;i++){System.out.println(candidate[i]+" ");}}public static void main(String args[]){int ID[]={1,1,1,2,2,2,3,3,3,1,2,3,1,2,3,6};int N=16;int candidate[] = {-1,-1,-1};System.out.println("打印ID列表");for(int i=0;i<N;i++){System.out.println(ID[i]);}Find(ID,N,candidate);} }(三)實(shí)驗(yàn)截圖:
轉(zhuǎn)載于:https://www.cnblogs.com/hehejeson/articles/5530299.html
總結(jié)