defaultdict 4

[LeetCode] 229. Majority Element II

'169. Majority Element'에서 난이도가 조금 올라간 문제지만 큰 틀에선 똑같기에 솔루션 역시 흡사하다. Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. Example 1: Input: nums = [3,2,3] Output: [3] Example 2: Input: nums = [1] Output: [1] class Solution: def majorityElement(self, nums: List[int]) -> List[int]: dic = defaultdict(int) for i, n in enumerate(nums): dic[n] += 1 ret = [] for i, k i..

[LeetCode] 169. Majority Element

1150번과 매우 유사한 문제다. 다만 다른 점은 해당 문제에선 Majority Element가 반드시 있다는 가정하에 이를 반환하는 것이고, 1150은 input으로 주어진 숫자가 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 in the array. Example 1: Input: nums = [3,2,3] Output: 3 Example 2: In..

[LeetCode] 582. Kill Process

Computer Science를 공부한 사람이라면 익숙한 pid(process id)와 ppid(parent process id)의 개념이 담긴 문제다. 해당 문제에서 각 process는 1개의 parent process만을 가질 수 있고 반면에 parent process는 여러 child process를 가질 수 있다. 해당 문제의 예시 그림으론 Tree 형태로 제시가 됐고, kill을 하기 위한 pid가 input으로 주어지고, 해당 process를 비롯해 연쇄적으로 모든 child process를 kill을 하기 위해 필요한 모든 pid를 List의 형태로 반환하는 문제다. Input: pid = [1,3,10,5], ppid = [3,0,5,3], kill = 5 Output: [5,10] Exp..

[LeetCode] 359. Logger Rate Limiter

같은 message가 10초 안에 다시 Print 되지 않도록 확인하는 함수를 만들면 된다. 파이썬의 해시맵을 사용해 해당 message의 timestamp를 확인하고 갱신해 True/False를 반환한다. class Logger: def __init__(self): self.d = defaultdict(int) def shouldPrintMessage(self, timestamp: int, message: str) -> bool: if message not in self.d: self.d[message] = timestamp return True else: if timestamp - self.d[message] < 10: return False else: self.d[message] = timestam..