Majority Element

초보개발·2023년 8월 24일
0

leetcode

목록 보기
9/39

Majority Element

https://leetcode.com/problems/majority-element/?envType=study-plan-v2&envId=top-interview-150

문제 요약

nums 배열에서 가장 많이 등장하는 숫자 return

풀이

  • Counter를 사용하여 nums 배열의 숫자를 센다
  • most_common() 메서드를 사용하여 가장 많이 등장한 숫자 순으로 정렬한다
  • 가장 맨 앞의 원소를 리턴한다

수도 코드

def sol(nums):
	cnt = Counter(nums)
    sorted_cnt = cnt.most_common() # [숫자, 횟수]
    return sorted_cnt[0][0]

Solution(Runtime: 135ms)

from collections import Counter

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        return Counter(nums).most_common()[0][0]

collections의 Counter를 사용하여 간단하게 풀이했다. 다른사람의 풀이를 보면 nums 배열을 순회하면서 요소와 횟수를 저장하고 가장 많이 등장한 숫자를 찾는다. 가장 많은 숫자만 찾으면 되기 때문에 Counter보다 변수만 사용하면 공간 복잡도가 줄어들 것이라고 생각한다.

0개의 댓글