【LeetCode】169. Majority Element

题目:

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

题解:

Solution 1 ()

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int n = nums.size();
        int cnt = 0, majority = 0;
        for(auto n : nums) {
            if(majority == n) cnt++;
            else {
                cnt--;
                if(cnt <= 0) {
                    cnt = 1;
                    majority = n;
                } 
            }
        }
        return majority;    
    }
};

Solution 2 ()

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        unordered_map<int, int> counts; 
        int n = nums.size();
        for (int i = 0; i < n; i++)
            if (++counts[nums[i]] > n / 2)
                return nums[i];
        
    }
};

Solution 3 ()

class Solution {
public:
    int majorityElement(vector<int>& nums) {
            sort(nums.begin(), nums.end());
    return nums[nums.size() / 2];
    }
};

Solution 4 ()

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int ret = 0;
        for(int i=0; i<32; ++i) {
            int ones = 0, zeros = 0;
            for(int j=0; j<nums.size(); ++j) {
                if((nums[j] & (1<<i)) != 0) ++ones;
                else ++zeros;
            }
            if(ones > zeros) ret |= (1<<i);
        }   
        return ret;
    }
};

Solution 5 ()

class Solution {
public:
    int majorityElement(vector<int> nums) {
        int n = nums.size();
        if(n <= 1) return nums[0];
        int m1 = majorityElement(vector<int> (nums.begin(), nums.begin() + n/2));
        int m2 = majorityElement(vector<int> (nums.begin() + n/2, nums.end()));
        if(m1 == m2) return m1;
        int cnt = 0;
        for(auto num:nums) {
            if(num == m1) cnt++;
            if(cnt > n/2) return m1;
        }
        return m2;
    }
};

 

posted @ 2017-05-07 21:30  Vincent丶丶  阅读(166)  评论(0编辑  收藏  举报