📖저자님의 책 소개 영상: https://www.youtube.com/watch?v=Q13Uj_5bH9M
🗓️TIL (this week I learned)
월 읽기, 정리
화 정리 - 더 해야 함
토 몸풀기 문제 + ⭐별 한 개 문제
일 여행준비 ㅠㅠㅠㅠ
알고리즘의 효율을 크게 높여줌
출처: 삽입정렬 wiki(en)
출처: 병합정렬 wiki(en)
출처: wiki(ko)
우선순위 큐는 힙으로 구현하는 것이 가장 좋다.
그 이유: 최소힙이나 최대힙이 특정 값을 루트 노드에 유지하는 특징이 있고, 우선 순위 큐의 핵심 동작(우선 순위가 높은 데이터부터 먼저 처리하는)과 맞아 떨어져서
파이썬 모듈: heapq
https://school.programmers.co.kr/learn/courses/30/lessons/12915
from operator import itemgetter
def solution(strings, n):
alphabet_sorted = sorted(strings)
return sorted(alphabet_sorted, key = itemgetter(n))
lambda가 편하긴 하다...
https://school.programmers.co.kr/learn/courses/30/lessons/12933
def solution(n: int) -> int:
s = str(n)
sorted_digits = sorted(s, reverse = True)
return int("".join(sorted_digits))
https://school.programmers.co.kr/learn/courses/30/lessons/42748
from typing import List, Tuple
def solution(array: List[int], commands: List[Tuple[int, int, int]]) -> List[int]:
answer: List[int] = []
for i, j, k in commands:
answer.append(sorted(array[i-1:j])[k-1])
return answer
https://school.programmers.co.kr/learn/courses/30/lessons/42746
from functools import cmp_to_key
from typing import List
def solution(numbers:List[int]) -> str:
strs: List[str] = list(map(str, numbers))
def compare(a: str, b: str) -> int:
if a + b > b + a:
return -1
if a + b < b + a:
return 1
return 0
sorted_strs = sorted(strs, key=cmp_to_key(compare))
result = "".join(sorted_strs)
if result[0] != "0":
return result
else:
return "0"
https://school.programmers.co.kr/learn/courses/30/lessons/64065
from typing import List
def solution(s: str) -> List[int]:
inner = s[2:-2]
subset_strings = inner.split("},{")
subsets: List[List[int]] = []
for subset_str in subset_strings:
number_strings = subset_str.split(",")
numbers = [int(num) for num in number_strings]
subsets.append(numbers)
subsets.sort(key=len)
result: List[int] = []
seen = set()
for subset in subsets:
for num in subset:
if num not in seen:
seen.add(num)
result.append(num)
return result
https://school.programmers.co.kr/learn/courses/30/lessons/62050
from heapq import heappush, heappop
from typing import List, Tuple
def solution(land: List[List[int]], height: int) -> int:
n = len(land)
visited: List[List[bool]] = [[False] * n for _ in range(n)]
total_cost = 0
# 상, 우, 하, 좌
directions: List[Tuple[int, int]] = [(-1, 0), (0, 1), (1, 0), (0, -1)]
# 우선순위 큐: 현재 칸까지 누적비용, 행, 열
pq : List[Tuple[int, int, int]] = []
heappush(pq, (0, 0, 0))
# 주변 노드 탐색
di = [-1, 0, 1, 0]
dj = [0, 1, 0, -1]
visited = [[False] * n for _ in range(n)]
# 시작 노드 추가
q = []
heappush(q, [0,0,0])
while pq:
cost, r, c = heappop(pq)
if visited[r][c]:
# 이미 처리한 칸이면 건너뛰기
continue
visited[r][c] = True
total_cost += cost
for dr, dc, in directions:
nr, nc = r + dr, c + dc
if not(0 <= nr < n and 0 <= nc < n):
continue
if visited[nr][nc]:
continue
diff = abs(land[r][c] - land[nr][nc])
# 높이차가 height보다 크면 diff, 아니면 0
move_cost = diff if diff > height else 0
heappush(pq, (move_cost, nr, nc))
return total_cost
https://school.programmers.co.kr/learn/courses/30/lessons/70129
from typing import List
def decimal_to_binary(n: int) -> str:
if n == 0:
return '0'
result: str = ""
while (n > 0):
result = str(n % 2) + result
n //= 2
return result
def solution(s: str) -> List[int]:
count_transform: int = 0
count_removed_zeros: int = 0
while (s != "1"):
zeros: int = s.count('0')
count_removed_zeros += zeros
s = s.replace('0', '')
length: int = len(s)
s = decimal_to_binary(length)
count_transform += 1
return [count_transform, count_removed_zeros]
https://school.programmers.co.kr/learn/courses/30/lessons/132265
from collections import Counter
from typing import List
# 풀이가 이해되지 않아서 우선 답을 차근차근 따라가봄
def solution(topping: List[int]) -> int:
# 결과값을 저장할 변수 초기화
split_count: int = 0
# 토핑의 개수를 세어서 딕셔너리에 저장
topping_counter: Counter = Counter(topping)
# 절반에 속한 토핑의 종류를 저장할 집합
half_topping_set: set = set()
# 롤케이크를 하나씩 절반에 넣으면서 확인
for t in topping:
# 절반에 토핑을 추가하고, 해당 토핑의 전체 개수를 줄임
half_topping_set.add(t)
topping_counter[t] -= 1
# 토핑의 전체 개수가 0이면 딕셔너리에서 제거
if topping_counter[t] == 0:
topping_counter.pop(t)
if len(half_topping_set) == len(topping_counter):
split_count += 1
# 공평하게 나눌 수 있는 방법의 수 반환
return split_count
https://school.programmers.co.kr/learn/courses/30/lessons/42842
from typing import List, Optional, Tuple
def solution(brown: int, yellow: int) -> List[int]:
total : int = brown + yellow
for width in range(3, int(total **0.5) + 1):
if total % width == 0:
height = total // width
yellow_area = (width - 2) * (height - 2)
if yellow_area == yellow:
return [max(width, height), min(width, height)]
return None
https://school.programmers.co.kr/learn/courses/30/lessons/12980
def solution(n: int) -> int:
bettery_usage = 0
while (n > 0):
if n % 2 == 1:
n -= 1
bettery_usage += 1
else:
n //= 2
return bettery_usage
https://school.programmers.co.kr/learn/courses/30/lessons/120861