Home LeetCode - 169. Majority Element
Post
Cancel

LeetCode - 169. Majority Element

169. Majority Element - easy

문제

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.

제한사항

입출력 예

1
2
3
4
5
6
7
Example 1:
Input: [3,2,3]
Output: 3

Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2

풀이

  • Divide and Conquer, Hash
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int majorityCount = nums.size() / 2;
        map<int, int> m;
        
        for(auto& i : nums)
            ++m[i];
        
        for(auto& i : m){
            if(i.second > majorityCount)
                return i.first;
        }

        return 0;
    }
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func majorityElement(nums []int) int {
    result := 0
    comp := 0
    m := make(map[int]int)
    
    for _, v := range(nums) {
        m[v]++
        
        if(comp < m[v]) {
            comp = m[v]
            result = v
        }
    }
    
    return result
}
This post is licensed under CC BY 4.0 by the author.