Given an array of size n, find the majority element. The majority element is the element, the appears more than times ⌊ n/2 ⌋ .
Assume that the array was non-empty and the majority element always exist in the array.
Topic:
Give an array to find the number of people in the array, the number of occurrences is greater than the sum of the number of occurrences of all other numbers.
Suppose the array is not empty and the majority must exist
Idea: Method 1:hashmap
By iterating through the array, each number of the array is counted by HashMap to count the number of occurrences, and if a number exceeds half, the number is the majority.
The complexity of time space is O (n)
Method 2:moore Voting algorithm
In the case of a majority, each time two different numbers are thrown away, the number remains the same, and the final number must be the majority.
- Throw away a number and a non-majority, the number is the same
- Throw away two non-majority, and the number is the same
Time complexity O (n), Spatial complexity O (1)
Code:
classSolution { Public: //Hash_map Method intMajorityElement1 (vector<int> &num) { intn =num.size (); if(n==1)returnnum[0]; Map<int,int>m; for(vector<int>::iterator It=num.begin (); It!=num.end (); it++) {m[*it]+=1; if(M[*it] > Floor (n/2)) return*it; } } //Moore Voting algorithm intMajorityElement2 (vector<int> &num) { intn=num.size (); if(n==1)returnnum[0]; intCount=0; intx; for(intI=0; i<n;i++){ if(count==0) {x=Num[i]; Count=1; } Else if(x==Num[i])++count; Else--count; } returnx;};
(Leetcode 169) Majority Element