[LeetCode] Majority Element 파이썬 (dict, Counter, median)
nums = [2,2,1,1,1,2,2] d = dict() for n in nums: if n in d: d[n] += 1 else: d[n] = 0 print(d) print(sorted(d.items(), key=lambda x: -x[1])[0][0]) # output # {2: 3, 1: 2} # [(2, 3), (1, 2)] #(key, value) # 2 dict에 넣어서 sorted key items()로 iterable하게 만든 다음 tuple로 나오는 값 중에서 뒤의 value 인 x[1]을 기준으로 오름차순으로 해야하기 때문에 -x[1] 으로 해준다. 제일 앞에 있는 tuple 중에서 key값을 return 해야되기 때문에 [0][0]
2021. 4. 2.
[LeetCode] Linked List Cycle 파이썬 (is operator, id)
2가지 풀이법(1: fast & slow, 2: marked as read) 풀이 1 (fast, slow) class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param head, a ListNode # @return a boolean def hasCycle(self, head): fast, slow = head, head while fast and fast.next: fast, slow = fast.next.next, slow.next if fast is slow: return True return False 어떻게 풀어야 할지 전혀 감이 안왔던 문제 fast, slow라는 2개의 head 의 c..
2021. 4. 1.