[Leetcode] Majority Element

Source: Internet
Author: User

Well, if you had got this problem accepted, you may have noticed that there is 7 suggested solutions for this problem. The following passage would implement 6 of them except the O(n^2) brute force algorithm.

Hash Table

The hash-table solution is very straightforward. We maintain a mapping from each element to its number of appearances. While constructing the mapping, we update the majority element based on the max number of appearances we have seen. Notice that we don't need to construct the full mapping when we see that an element have appeared more than times n / 2 .

The code is as follows and which should be self-explanatory.

1 classSolution {2  Public:3     intMajorityelement (vector<int>&nums) {4unordered_map<int,int>counts;5         intMajor, Max_counts =0, n =nums.size ();6          for(inti =0; I < n; i++) {7counts[nums[i]]++;8             if(Counts[nums[i]) >max_counts) {9Max_counts =Counts[nums[i]];TenMajor =Nums[i]; One                 if(Max_counts > N/2) Break; A             } -         } -         returnMajor; the     } -};

Sorting

Since The majority element appears more than  n/2  times, the  n/2 -th Element In the sorted nums  must is the the majority element. This can is proved intuitively. Note that the majority element would take more than , N/2  positions in the sorted  nums  (cover more than half of  nums ). If the first of it appears in the  0 -th position, it'll also appear in the  n/2 -th p Osition to cover more than half of  nums . It is similar if the last of it appears in the  n-1 -th position. These cases is, the contiguous chunk of the majority element is to the leftmost and the rightmost in  N UMS . For other cases (imagine the chunk moves between the left and the right end), it must also appear in the  n/2< /code>-th position.

The code is as follows, being very short if we use the system sort .

1 class Solution {2public:3     int majorityelement (vector<int>& nums) {4        sort ( Nums.begin (), Nums.end ()); 5         return 2 ]; 6     }7 };

Randomization

This was a really nice idea and works pretty well (16ms running time on the OJ, almost fastest among the C + + solutions). The proof is already given in the suggested solutions.

The code is as follows, randomly pick a element and see if it is the majority one.

1 classSolution {2  Public:3     intMajorityelement (vector<int>&nums) {4         intn =nums.size ();5 Srand (Unsigned (Time (NULL)));6          while(true) {7             intIDX = rand ()%N;8             intcandidate =Nums[idx];9             intCounts =0; Ten              for(inti =0; I < n; i++) One                 if(Nums[i] = =candidate) Acounts++; -             if(Counts > N/2)returncandidate; -         } the     } -};

Divide and Conquer

This is very algorithmic. However, the implementation of it requires some careful thought about the base cases of the recursion. The base case was the when the array had only one element and then it was the majority one. Moreover, this solution was relatively slow in practice.

1 classSolution {2  Public:3     intMajorityelement (vector<int>&nums) {4         returnMajority (Nums,0, Nums.size ()-1);5     }6 Private:7     intMajority (vector<int>& Nums,intLeftintRight ) {8         if(left = right)returnNums[left];9         intMid = left + ((right-left) >>1);Ten         intLM =majority (Nums, left, mid); One         intRM = Majority (Nums, Mid +1, right); A         if(lm = = RM)returnLM; -         returnCounts (Nums, LM) > counts (nums, RM)?lm:rm; -     } the     intCounts (vector<int>& Nums,intelem) { -         intCNT =0; -          for(inti =0; I <int(Nums.size ()); i++) -             if(Nums[i] = = elem) cnt++; +         returnCNT; -     } +};

Moore Voting algorithm

A Brilliant and Easy-to-implement algorithm! It also runs very fast, about 20ms.

1 classSolution {2  Public:3     intMajorityelement (vector<int>&nums) {4         intMajor, Counts =0, n =nums.size ();5          for(inti =0; I < n; i++) {6             if(!counts) {7Major =Nums[i];8Counts =1;9             }Ten             ElseCounts + = (nums[i] = = major)?1: -1; One         } A         returnMajor; -     } -};

Bit manipulation

Another nice idea! The key lies in how to count the number of 1 ' s on a specific bit. Specifically, you need a with a in the mask 1 i -the bit and 0 otherwise to get the i -th bit for each Element in nums . The code is as follows.

1 classSolution {2  Public:3     intMajorityelement (vector<int>&nums) {4         intMajor =0, n =nums.size ();5          for(inti =0, mask =1; I < +; i++, Mask <<=1) {6             intBitcounts =0;7              for(intj =0; J < N; J + +) {8                 if(Nums[j] & mask) bitcounts++;9                 if(Bitcounts > N/2) {TenMajor |=Mask; One                      Break; A                 } -             } -         }  the         returnMajor; -     }  -};

[Leetcode] Majority Element

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.