Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- Python
- Medium
- 재귀
- easy
- Binary
- Depth-first Search
- tree
- leetcode
- linked list
- 중간
- string
- 쉬움
- dfs
- matrix
- HashTable
- 문자열
- recursive
- sorting
- backtracking
- two pointers
- 이진트리
- binary search
- binary tree
- DP
- 미디움
- list
- 리트코드
- Array
- math
- hash table
Archives
- Today
- Total
부부의 코딩 성장 일기
LeetCode 169(Majority Element, Python) 본문
1. 문제 링크
Majority Element - LeetCode
Can you solve this real interview question? Majority Element - Given an array nums of size n, return the majority element. The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists
leetcode.com
2. 문제 설명
- 크기가 n인 배열이 주어졌을 때, majority element를 반환
- 여기서 majority element란, 배열 내에서 [n/2] 번 이상 존재한 element를 의미하며,
- 배열 내에 majority element가 존재한다고 가정 ← 문제를 쉽게 만드는 요인
- 예시1) [3,2,3] 이면 3이 배열에 2번(3/2보다 큰) 등장했으므로 3 반환
- 예시2) [2,2,1,1,1,2,2] 에 2가 4번(7/2보다 큰) 등장했으므로 2 반환
3. 처음 풀이
- history_dict에 element별 count를 센다.
- 가장 큰 value를 가진 key가 당연히 majority element가 된다.
class Solution:
def majorityElement(self, nums: List[int]) -> int:
history_dict = {} # hash table을 위한 빈 dict
for i in nums: # for문을 돌리며
if i not in history_dict: # element가 처음 등장하면 1을 넣고
history_dict[i] = 1
else:
history_dict[i] += 1 # 이미 등장한 경우 1씩 더해주면서, key별 count를 센다
return max(history_dict, key=history_dict.get) #그리고 dict의 가장 큰 value를 가진 key를 반환
- 생각보다 심플하게 풀렸고, runtime 92.57 beats, memory 96.26 beats로 결과도 잘나옴
4. 다른 풀이
- 다른사람 풀이 중에 신박했던 풀이
- 그냥 sort를 시킨 후에, k//2 번째 element를 불러오면, majority element가 된다.
class Solution:
def majorityElement(self, nums: List[int]) -> int:
nums.sort()
k = len(nums)
return nums[k//2]
- 아래 풀이는 hash table 없이 list.count(element)를 비교해가면서 반환
class Solution:
def majorityElement(self, nums: List[int]) -> int:
unique = set(nums)
for num in unique:
if nums.count(num) > len(nums) / 2:
return num
5. 배운 점
- hash table을 잘 활용하기!
'Algorithm > LeetCode' 카테고리의 다른 글
LeetCode 190(Reverse Bits, Python) (1) | 2023.12.07 |
---|---|
LeetCode 171(Excel Sheet Column Number, Python) (0) | 2023.12.06 |
LeetCode 168(Excel Sheet Column Title, Python) (0) | 2023.12.04 |
LeetCode 160(Intersection of Two Linked Lists, Python) (1) | 2023.12.03 |
LeetCode 144(Binary Tree Preorder Traversal, Python) (0) | 2023.12.02 |