[LeetCode][Python3] 169. Majority Element
2018. 10. 1. 00:41 |
프로그래밍/LeetCode
Problem :
https://leetcode.com/problems/majority-element/description/
My Solution :
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
counter = {}
for n in nums:
counter[n] = counter.setdefault(n, 0) + 1
for n, count in counter.items():
if count > len(nums) // 2:
return n
Comment :
위 풀이는 문제를 처음 접했을 때 별 고민없이 접근했던 방법이다.
아래 풀이는 내가 몰랐던 Boyer–Moore majority vote algorithm을 이용한 것이다.
My Solution2 :
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = 0
major = None
for n in nums:
if count == 0:
major = n
if n == major:
count += 1
else:
count -= 1
return major
'프로그래밍 > LeetCode' 카테고리의 다른 글
[LeetCode][Python3] 234. Palindrome Linked List (0) | 2018.10.04 |
---|---|
[LeetCode][Python3] 226. Invert Binary Tree (0) | 2018.10.03 |
[LeetCode][Python3] 206. Reverse Linked List (0) | 2018.10.01 |
[LeetCode][Python3] 198. House Robber (0) | 2018.10.01 |
[LeetCode][Python3] 160. Intersection of Two Linked Lists (0) | 2018.09.28 |
[LeetCode][Python3] 155. Min Stack (0) | 2018.09.28 |
[LeetCode][Python3] 141. Linked List Cycle (0) | 2018.09.28 |
[LeetCode][Python3] 136. Single Number (0) | 2018.09.27 |
최근에 달린 댓글 최근에 달린 댓글