美文网首页Leetcode
Leetcode 169. Majority Element

Leetcode 169. Majority Element

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

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

    1. Description

    Majority Element

    2. Solution

    • Version 1
    class Solution {
    public:
        int majorityElement(vector<int>& nums) {
            int n = nums.size() / 2;
            unordered_map<int, int> m;
            for(int num : nums) {
                m[num]++;
                if(m[num] > n) {
                    return num;
                }
            }
        }
    };
    
    • Version 2
    class Solution {
    public:
        int majorityElement(vector<int>& nums) {
            int count = 0;
            int candidate = 0;
            for(int num : nums) {
                if(count == 0) {
                    candidate = num;
                }
                count += (candidate==num?1:-1); 
            }
            return candidate;
        }
    };
    

    Reference

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

    相关文章

      网友评论

        本文标题:Leetcode 169. Majority Element

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