Skip to content

Commit 5862e65

Browse files
authored
Merge pull request #2531 from kangdaia/main
[kangdaia] WEEK 6 solutions
2 parents b422044 + b41a689 commit 5862e65

3 files changed

Lines changed: 84 additions & 0 deletions

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class Solution:
2+
def maxArea(self, height: list[int]) -> int:
3+
# 가장 멀리 떨어져 있으면서 높이가 비슷한 막대기?
4+
max_area = 0
5+
i, j = 0, len(height) - 1
6+
while i < j:
7+
left, right = height[i], height[j]
8+
area = min(left, right) * (j - i)
9+
if area > max_area:
10+
max_area = area
11+
if left < right:
12+
i += 1
13+
else:
14+
j -= 1
15+
return max_area

spiral-matrix/kangdaia.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
class Solution:
2+
def spiralOrder(self, matrix: list[list[int]]) -> list[int]:
3+
"""
4+
주어진 2D 행렬을 나선형으로 순회하여 요소들을 반환하는 함수
5+
6+
방법:
7+
1. transpose 행렬을 만들어 열을 쉽게 접근할 수 있도록 함
8+
2. while 루프를 사용하여 나선형으로 순회
9+
3. 각 단계에서 top row, right column, bottom row, left column을 순서대로 추가
10+
4. 각 단계가 끝날 때마다 row와 col을 증가시켜 다음 레이어로 이동
11+
12+
시간복잡도 O(m*n), 공간복잡도 O(m*n)
13+
14+
Args:
15+
matrix (list[list[int]]): 2D 행렬
16+
17+
Returns:
18+
list[int]: 나선형으로 순회한 요소들의 리스트
19+
"""
20+
row, col = 0, 0
21+
m, n = len(matrix), len(matrix[0])
22+
t_matrix = list(zip(*matrix))
23+
spiral = []
24+
while row < m and col < n:
25+
top, left = row, col
26+
bottom, right = m - row - 1, n - col - 1
27+
if top > bottom or left > right:
28+
break
29+
# first row: left -> right
30+
first_row = matrix[top][left : right + 1]
31+
spiral += first_row
32+
# last col: top+1 -> bottom
33+
last_col = list(t_matrix[right][top + 1 : bottom + 1])
34+
spiral += last_col
35+
# last row: right-1 -> left (역순)
36+
if top < bottom:
37+
last_row = matrix[bottom][left:right][::-1]
38+
spiral += last_row
39+
# first col: bottom-1 -> top+1 (역순)
40+
if left < right:
41+
first_col = list(t_matrix[left][top + 1 : bottom][::-1])
42+
spiral += first_col
43+
# add
44+
row += 1
45+
col += 1
46+
return spiral

valid-parentheses/kangdaia.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution:
2+
def isValid(self, s: str) -> bool:
3+
"""s에 있는 bracket들의 쌍이 맞는지 확인하는 함수
4+
시간 복잡도: O(n), 공간 복잡도: O(n)
5+
6+
Args:
7+
s (str): bracket {}, [], ()로 이루어진 문자열
8+
9+
Returns:
10+
bool: bracket들의 쌍이 맞는지 여부
11+
"""
12+
stack = []
13+
pair = {"{": "}", "[": "]", "(": ")"}
14+
for ch in s:
15+
if ch in pair:
16+
stack.append(ch)
17+
elif len(stack) == 0:
18+
return False
19+
else:
20+
last = stack.pop()
21+
if pair[last] != ch:
22+
return False
23+
return True if len(stack) == 0 else False

0 commit comments

Comments
 (0)