美文网首页Leetcode
Leetcode 229. Majority Element I

Leetcode 229. Majority Element I

作者: SnailTyan | 来源:发表于2018-09-13 18:56 被阅读3次

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Majority Element II

2. Solution

  • Version 1
class Solution {
public:
    vector<int> majorityElement(vector<int>& nums) {
        int limit = nums.size() / 3;
        vector<int> result;
        unordered_map<int, int> m;
        for(int num : nums) {
            m[num]++;
            if(m[num] > limit) {
                m[num] = INT_MIN;
                result.push_back(num);
            }
        }
        return result;
    }
};
  • Version 2
class Solution {
public:
    vector<int> majorityElement(vector<int>& nums) {
        vector<int> result;
        int limit = nums.size() / 3;
        int candidate1 = 0, candidate2 = 0;
        int count1 = 0, count2 = 0;
        for(int num : nums) {
            if(num == candidate1) {
                count1++;
            }
            else if(num == candidate2) {
                count2++;
            }
            else if(count1 == 0) {
                candidate1 = num;
                count1 = 1;
            }
            else if(count2 == 0) {
                candidate2 = num;
                count2 = 1;
            }
            else {
                count1--;
                count2--;
            }
        }
        count1 = 0;
        count2 = 0;
        for(int num : nums) {
            if(num == candidate1) {
                count1++;
            }
            else if(num == candidate2) {
                count2++;
            }
        }
        if(count1 > limit) {
            result.push_back(candidate1);
        }
        if(count2 > limit) {
            result.push_back(candidate2);
        }
        return result;
    }
};

Reference

  1. https://leetcode.com/problems/majority-element-ii/description/

相关文章

网友评论

    本文标题:Leetcode 229. Majority Element I

    本文链接:https://www.haomeiwen.com/subject/ihbwgftx.html