Well, this problem becomes a little trickier since there could be more than one majority element. But, there can is at the most of the them. This can is proved using proof by contradiction. If there is not less than 3
majority element and each appears more than times, then would have n / 3
nums
3 * n / 3 > n
eleme NTS, which is a contradiction. Note that the does is not affect the correctness of this proof. You could try some examples and convince yourself of this.
Now we maintain a for the vector<int> major
majority elements. Once we meet an element which had appeared more than times and had not n / 3
been added major
to, we add it to major
. For counting the number of appearances unordered_map<int, int> counts
. For telling whether it had been added, we use the A to unordered_set<int> exist
store the added elements.
Since we visit each element exactly once and the operations (search, insertion) w.r.t counts
and exist
(both is hash tables ) O(1)
is, the idea can simply was proved to be of O(n)
time-complexity.
The code is as follows.
1 classSolution {2 Public:3vector<int> Majorityelement (vector<int>&nums) {4vector<int>Major;5unordered_map<int,int>counts;6unordered_set<int>exist;7 intn =nums.size ();8 for(inti =0; I < n; i++) {9counts[nums[i]]++;Ten if(Counts[nums[i]] > N/3&& Exist.find (nums[i]) = =Exist.end ()) { One Major.push_back (Nums[i]); A Exist.insert (Nums[i]); - } - if(major.size () = =2) Break; the } - returnMajor; - } -};
[Leetcode] Majority Element II