ice rabbit programming

[LeetCode] Majority Element 본문

PS/LeetCode

[LeetCode] Majority Element

판교토끼 2020. 4. 21. 23:40

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

 

Majority Element - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

가장 많이 등장하는 원소를 찾아내는 문제이다. 별 생각 없이 map을 이용해 풀었다.

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int size = nums.size();
        map<int,int> counts;
        for(int i=0;i<size;i++) {
            if(counts.find(nums[i])==counts.end()) // 해당 key가 존재하는가?
                counts.insert(make_pair(nums[i],1));
            else
                (counts.find(nums[i])->second)++;
            if(counts.find(nums[i])->second > size/2)
                return nums[i];
        }
        return 0;
    }
};

40ms로 나왔음에도 C++에서 꽤 느린 축에 속했는데, 정렬 후에 가운데 원소를 반환하는 것이 가장 빨랐다.

ㅠㅠ 역시 쉽게 푸는 천재들이 많다.

'PS > LeetCode' 카테고리의 다른 글

[LeetCode] Add Binary  (0) 2020.04.23
[LeetCode] Same Tree  (0) 2020.04.22
[LeetCode] Pascal's Triangle  (0) 2020.04.20
[LeetCode] Maximum Depth of Binary Tree (feat. 고정관념?)  (0) 2020.04.20
[LeetCode] Minimum Depth of Binary Tree  (0) 2020.04.20