2025/01 106

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개 넘는..

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..

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)**에 초점을 맞..

Backtracking: 51. N-Queens

51. N-Queens https://youtu.be/Ph95IHmRp5M?si=nFzhZlWopNf9D4FI class Solution: def solveNQueens(self, n: int) -> List[List[str]]: """ - negDiag: ↖ ↘ 대각선 방향을 추적 (row - col = 일정한 값) - posDiag: ↗ ↙ 대각선 방향을 추적 (row + col = 일정한 값) - col: 퀸이 이미 배치된 열(column)을 추적 - 매 줄마다 퀸 하나씩 배치 가능 (한 행에 하나의 퀸만 존재) """ # 퀸이 배치된 열(colum..

Backtracking: 131. Palindrome Partitioning

131. Palindrome Partitioning https://youtu.be/3jvWodd7ht0?si=paC9K4J8hqA0IgZJ class Solution: def partition(self, s: str) -> List[List[str]]: # palindrome: 앞으로 읽으나 뒤로 읽으나 같은 문자열을 의미 res = [] # 모든 가능한 회문 분할 결과를 저장할 리스트 # 주어진 문자열이 palindrome인지 확인하는 함수 def isPalidrome(substring): # 문자열을 뒤집어서 비교하여 palindrome 여부 반환 return substring == substring[::..

Backtracking: 90. Subsets II

90. Subsets II https://youtu.be/Vn2v6ajA7U0?si=w1awdAmx7zve9Tqv class Solution: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: # Sort the input list to group duplicates together # 입력 리스트를 정렬하여 중복된 숫자를 연속적으로 배치 nums.sort() # List to store all unique subsets # 모든 고유한 부분집합을 저장할 리스트 res = [] # Backtracking function # 백트래킹 함수 정..