Title: Finding the Water king
Design ideas:
Suppose the first ID is the water king, with King record, the number of times recorded with the second, than the next ID if the same is times++, otherwise--; if times=0, the next one is designated as the Water King, and then proceed, the last times more than 0 that ID must be the water king, Because the number of occurrences is greater than half.
Code implementation:
Package test1; Public classforumking { Public Static voidMain (string[] args) {intid[]={1,1,4,1,1,8,1,7,5,1}; inttimes,king = id[0]; for(inti=times=0;i<Ten; i++) { if(times==0) {King=Id[i]; Times=1; } Else { if(id[i]==King) Times++; Else Times--; }} System. out. println ("Water King's ID:"+king); }}
Realize:
Personal Summary:
See the topic is always feel impossible, but think of the words feel this is greater than half or very mysterious, the eye is here, feel this algorithm and the algorithm is very similar to the elimination, but temporarily can only think of so many.
Class practice-Finding water king