[Leetcode] Majority Element II

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.