Given an array of integers, the majority number is the number of this occurs more than 1/3 of the size of the array. Find it. Notethereis a majority number in the Arrayexamplefor [return 1challengeo (n) Time and O (1) s Pace
33 offset law, but there are also areas to note:
1. When we subtract from Cnt1,cnt2, we discard 3 digits (current number, candidate1, Candidate2). That is, every time we discard a number, we discard 3 different numbers.
and majority number exceeds 1/3 so it will eventually stay.
The total number of sets is N, majority number is M. The number of drops is x. The number of times the majority is thrown is x.
and M > n/3, n-3x > 0.
3m > N, n > 3x so 3m > 3x, M > x that means M must not be thrown out.
In the worst case, Majority number is thrown away every time, but it is bound to be in n1,n2.
2. Why do I have to check 2 more numbers at the end (counting from the beginning, not the rest of count1, Count2)? Because the number of majority can be excessively consumed, so that its count is less than N2, or equal to N2. The example above is.
Another example:
1 1 1 1 2 3 2 3 4 4 4 This 1 will be consumed too much and the last remaining is less than 4.
1 Public classSolution {2 /**3 * @paramnums:a List of integers4 * @return: The majority number that occurs more than 1/35 */6 Public intMajoritynumber (arraylist<integer>nums) {7 //Write your code8 intcandidate1 = 0;9 intCandidate2 = 0;Ten intCount1 = 0; One intCount2 = 0; A for(intelem:nums) { - if(Count1 = = 0) { -Candidate1 =Elem; the } - if(Count2 = = 0 && Elem! =candidate1) { -Candidate2 =Elem; - } + if(Candidate1 = =elem) { -count1++; + } A if(Candidate2 = =elem) { atcount2++; - } - if(candidate1! = Elem && Candidate2! =elem) { -count1--; -count2--; - } in } - toCount1 = 0; +Count2 = 0; - for(intelem:nums) { the if(Elem = = candidate1) count1++; * Else if(Elem = = Candidate2) count2++; $ }Panax Notoginseng returnCount1>count2?Candidate1:candidate2; - } the}
Lintcode:majority number II