169. Majority Element (Easy)

1.問題

  • 給予一個大小為n的array, 找出出現次數大於一半的成員

2.想法

  • 用多個vector儲存數字所出現的次數, 如果次數出現數量超過一半則回傳該數字

3.程式碼

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

4.Performance

Last updated