码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】169. Majority Element

时间:2017-05-07 22:03:59      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:题目   nes   style   public   div   appears   sort   empty   map   

题目:

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;
    }
};

 

【LeetCode】169. Majority Element

标签:题目   nes   style   public   div   appears   sort   empty   map   

原文地址:http://www.cnblogs.com/Atanisi/p/6803708.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!