Hashmap: 217. Contains Duplicate 217. Contains Duplicate class Solution: def containsDuplicate(self, nums: List[int]) -> bool: hashmap = {} for num in nums: if num not in hashmap: hashmap[num]=1 else: hashmap[num] += 1 return True return False LeetCode/주제별 보충 2025.01.20
Heap-PrioiryQueue: 621. Task Scheduler ★★★ 621. Task Scheduler class Solution: def leastInterval(self, tasks: List[str], n: int) -> int: # each task takes 1 unit of time # minimize idle time # 각 작업은 1 단위 시간만 소요되며, 유휴 시간을 최소화하는 것이 목표 # Count the frequency of each task # 각 작업의 빈도를 세어서 저장 count = Counter(tasks) # 예: {"A": 3, "B": 3, "C": 1} # Convert the task counts to a max heap (negativ.. LeetCode/주제별 보충 2025.01.20
Heap-PrioiryQueue: 215. Kth Largest Element in an Array ★ 215. Kth Largest Element in an Array class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: # minheap 으로 만들고, k개 까지. 힙 개수 유지하게 하면, # k 개 보다 많으면 작은 것들 제거 # 그렇게 하면, minheap[0]에는 k번째 큰 것이 남아있음 heapq.heapify(nums) while( len(nums) > k): heapq.heappop(nums) return nums[0] 메모리 절약을 위해, k 개 만큼 우선 넣어서, minheap 만들고.1개씩 추가해서, k개 넘는.. LeetCode/주제별 보충 2025.01.20
Heap-PrioiryQueue: 973. K Closest Points to Origin ★ 973. K Closest Points to Origin https://youtu.be/rI2EBUEMfTk?si=rQzq5oqyjL2M1qgb class Solution: def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: # k번째 가까운 points 리턴, # [distance, x, y] 로 저장 # minHeap 사용 minHeap = [] for x, y in points: dist = (x**2) + (y**2) minHeap.append([dist, x, y]) heapq.heapify(minHe.. LeetCode/주제별 보충 2025.01.20
Heap-PrioiryQueue: 1046. Last Stone Weight 1046. Last Stone Weight https://youtu.be/B-QCq79-Vfw?si=3xrwdkwlsVfUMrM8 class Solution: def lastStoneWeight(self, stones: List[int]) -> int: # 기본적으로 minHeap 이니깐, -1 곱하면 maxheap stones = [-s for s in stones] heapq.heapify(stones) print(stones) while len(stones) > 1: high_1st = heapq.heappop(stones) high_2nd = heapq.heappop(stones) .. LeetCode/주제별 보충 2025.01.20
Heap-PrioiryQueue: 703. Kth Largest Element in a Stream ★ 703. Kth Largest Element in a Stream https://youtu.be/hOjcdrqMoQ8?si=j-8DMVDjR9t8bNx_ class KthLargest: def __init__(self, k: int, nums: List[int]): self.k = k self.minHeap = nums heapq.heapify(self.minHeap) # 최소 힙의 크기를 k 개로 유지하기 위한 로직 while len(self.minHeap) > k: # nums 리스트의 길이가 k보다 큰 경우, # 가장 작은 값을 하나씩 제거하여 힙의 크기를 k로 줄임 he.. LeetCode/주제별 보충 2025.01.20
Heap / Priority Que 힙, 우선순위큐 는 완전 이진 트리 임그래서왼쪽 자식 index: 2*i오른쪽 자식 index: 2*i +1부모 index = i/2 단 행렬에서, index 는 1부터.. leftChild of i = heap[2 * i]rightChild of i = heap[(2 * i) + 1] parent of i = heap[i // 2] 힙(Heap)의 종류힙에는 크게 두 가지 유형이 있습니다:최소 힙 (Min Heap):루트 노드에 가장 작은 값이 위치합니다.가장 작은 값이 우선순위가 가장 높으며, 가장 먼저 제거됩니다.최대 힙 (Max Heap):루트 노드에 가장 큰 값이 위치합니다.가장 큰 값이 우선순위가 가장 높으며, 가장 먼저 제거됩니다.이번 내용에서는 **최소 힙(Min Heap)**에 초점을 맞.. Coding Test/알고리즘 이론 2025.01.20