Zero to Hero
article thumbnail
Published 2021. 4. 23. 11:01
169. Majority Element Algorithm
 

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

1. 해시맵 스타일(Dict, Counter 사용)

from collections import Counter

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        counter = Counter()
        for num in nums:
            counter[num] += 1
        return counter.most_common(1)[0][0]

 

2. 정렬 후 중앙값 반환

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        return sorted(nums)[len(nums) // 2]

3. Boyer-Moore Voting Algorithm

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        target, count = 0, 0
        for num in nums:
            if count == 0:
                target = num
            count += 1 if num == target else -1
        return target

 

굉장히 유익한 문제였다. 

'Algorithm' 카테고리의 다른 글

448. Find All Numbers Disappeared in an Array  (0) 2021.04.26
21. Merge Two Sorted Lists  (0) 2021.04.26
136. Single Number  (0) 2021.04.22
617. Merge Two Binary Trees  (0) 2021.04.21
14. Longest Common Prefix  (0) 2021.04.20
profile

Zero to Hero

@Doljae

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!