문제 : 크기가 N 인 list에서 N/2 이상 등장하는 원소를 반환하라
아이디어: 각 원소의 갯수 dictionary 에 저장해서 major한 값을 찾는다.
코드 :
class Solution:
def majorityElement(self, nums: List[int]) -> int:
ans = -1
d = dict()
for n in nums:
if n in d:
d[n] += 1
else:
d[n] = 1
for key in d:
if d[key] > (len(nums)//2):
ans = key
return ans
파이썬에서는 dictionary 라는 해시테이블 자료형을 제공한다
key 와 value를 어떻게 순회하는지 익혀두면 매우 유용하다.
출처 : leetcode.com/problems/majority-element/
'프로그래밍' 카테고리의 다른 글
leetcode 3. Longest Substring Without Repeating Characters 풀이 (0) | 2021.04.08 |
---|---|
leetcode 14. Longest Common Prefix 풀이 (0) | 2021.04.07 |
leetcode 11. Container With Most Water 풀이 (0) | 2021.04.01 |
leetcode 287. Find the Duplicate Number 풀이 (0) | 2021.04.01 |
leetcode 448. Find All Numbers Disappeared in an Array 풀이 (0) | 2021.03.31 |