thought : This topic generally requires O (n) time complexity and O (1) space, in order not to let you use HashMap to calculate the statistics. Here we can implement the idea of 22 elimination, such as an array of arr: 1 2 2 3 2 1 2, then we take the first element Arr[0] as the starting element K, its occurrence count value is 1, and then from the second element arr[1] begin to iterate over the array, if ARR[1] = = k, then we will put count++, if not equal, we will count--, if count is reduced to 0, then re-assign the current element Arr[i] to K,count re-assigned to the value of 1, and then continue this comparison. For this array, the last K must be 2, because 2 appears more than half the times.
Public Static voidSearchint[] arr) { if(Arr.length = = 0)return; intCount = 1;//number of times the save occurred intK = arr[0]; for(inti = 1; i < arr.length; i++) { if(k = = Arr[i]) count++; Else{Count--; if(count = = 0) {k=Arr[i]; Count= 1; } }} count= 0; //there may be no element more than half, so you need to judge again for(inti = 0; i < arr.length; i++) { if(Arr[i] = = k) count++; } if(Count > Arr.length/2) System.out.println (k); ElseSystem.out.println ("Not Found! "); }
Number of occurrences more than half in an array