In the interview problem often appear such a topic, to an array, which contains n non-negative elements, let you find the number of occurrences of more than half of the numbers in the group.
The first thing we think of when we see this is the solution of brute force, which is to order the array, output the middle element, because if the number of occurrences is more than half the order of the intermediate element is definitely the value we need.
In doing so, the time complexity of sorting is generally O (NLOGN), so is there a time-complexity-n algorithm?
The answer is of course there is, there is such an algorithm, Majority Vote algorithm, he is doing: set a counter count and save the most elements of the variable Majority,
- If count==0, the now value is set to the current element of the array, and the majority is assigned a value of 1;
- Conversely, if the majority and the current array element values are the same, then count++, and vice versa count--;
- Repeat these two steps until the array is scanned.
- Count is assigned a value of 0, and the array is scanned again from the beginning, and if the element values of the elements are the same as the majority values, count++ until the array is scanned.
- If the value of count at this time is greater than or equal to N/2, the value of majority is returned, and vice versa returns-1.
The simple implementation of the code is as follows:
Public intFind_majority (int[] Array) { intmajor=0, Count = 0; intI=0; while(i<array.length) { if(i==0) {Major=array[0]; Count=1; }Else if(Major==array[i]) {//if the array is scanned to the same number as the current majority number. count++; }Else if(major!=array[i]&&count!=0) {//if the array is not scanned and the current number of majority is not equal, the number of votes currently majority is at least one vote. count--; }Else{Major=Array[i]; } I++; } intTmp_count=0; for(intj=0;j<array.length;j++){ if(array[j]==Major) Tmp_count++; } if(tmp_count>= (array.length+1)/2)//Check if the number of majority votes exceeds half of the total number of votes returnMajor; Else return-1; }
Majority voting algorithm (Majority Vote algorithm)