Packagearraysum; Public classfindwaterking { Public Static voidMain (string[] args) {//Put the ID list in an array int[] Idnum = {1,1,1,1,12,3,11,1,1,15,6,6,77,1,1,1,1}; //Pointer to previous and next number intPrevior = 0; intNext = 1; //two-phase elimination through a while loop while((Previor < idnum.length-1) && (Next <idnum.length)) {//if the previous number and the next number are equal, the pointer moves backwards one if(Idnum[previor] = =Idnum[next]) {Previor= Previor + 1; Next= next + 1; } //if the previous number and the last number are not equal, the two numbers will eliminate each other and move the pointer two bits in a second. Else{Idnum[previor]=-1; Idnum[next]=-1; Previor= Previor + 2; Next= Next + 2; } } //22 Phase Elimination after the first found not-1 array element found the water king's IDNext = 0; while(Next <idnum.length) {if(Idnum[next]! =-1) {System.out.println (Idnum[next]); Break; } Else{Next= next + 1; } } }}
The essence of the question of finding water is how to quickly find more than half of the number of occurrences in a series of consecutive numbers. I used the idea provided by the teacher, put this string of numbers into an array, two adjacent numbers to do the comparison, if equal, in the backward comparison, if not the two numbers are not equal to 1, indicating that the two numbers have been offset each other. The number of water kings is the most, and the last array contains only the number of water kings and-1.
Find water king multiple water king