-
-
Notifications
You must be signed in to change notification settings - Fork 195
[taurus09318976.py] WEEK 06 Solutions #1448
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
54ee381
Create taurus09318976.py
taurus09318976 87a3d1d
Update taurus09318976.py
taurus09318976 9bbb9ed
Create taurus09318976.py
taurus09318976 02d8fc1
Update taurus09318976.py
taurus09318976 c2acdc6
Update taurus09318976.py
taurus09318976 2fd7637
Create taurus09318976.py
taurus09318976 c3a70d8
Update taurus09318976.py
taurus09318976 0ad15e0
Create taurus09318976.py
taurus09318976 f5cde09
Create taurus09318976.py
taurus09318976 4264f8b
Update taurus09318976.py
taurus09318976 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
''' | ||
이 문제는 주어진 높이 배열에서 두 개의 수직선을 선택해 최대 물의 양을 구하는 문제임 | ||
|
||
조건 : 1) 두 선 사이의 거리(너비) * 두 선 중 낮은 높이 = 물의 양 | ||
2) 물은 기울일 수 없으므로 높이는 낮은 선 기준임 | ||
|
||
해결 방법 : | ||
two pointers 접근법을 사용해서 | ||
왼쪽과 오른쪽 포인터를 배열의 시작과 끝에 배치함 | ||
더 낮은 높이를 가진 포인터를 안쪽으로 이동시키며 최대 물의 양을 계산함 | ||
|
||
''' | ||
|
||
class Solution: | ||
def maxArea(self, height: List[int]): | ||
# two pointers 초기화 | ||
left = 0 | ||
right = len(height) - 1 | ||
# 최대 물의 양을 저장할 변수 | ||
max_water = 0 | ||
|
||
# 포인터가 교차하기 전까지 반복 | ||
while left < right: | ||
# 두 선 사이의 거리 계산 | ||
width = right - left | ||
# 두 선 중 낮은 높이 계산 | ||
current_height = min(height[left], height[right]) | ||
# 현재 물의 양 계산 | ||
current_water = width * current_height | ||
|
||
# 최대 물의 양 계산 | ||
if current_water > max_water: | ||
max_water = current_water | ||
|
||
# 더 낮은 높이의 포인터 이동 | ||
if height[left] < height[right]: | ||
left += 1 | ||
else: | ||
right -= 1 | ||
|
||
return max_water | ||
|
||
|
||
|
52 changes: 52 additions & 0 deletions
52
design-add-and-search-words-data-structure/taurus09318976.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
''' | ||
이 문제는 단어를 추가하고, 검색할 때 .을 와일드 카드로 사용할 수 있는 자료구조를 구현해야 함 | ||
Trie 자료구조를 사용하여 .이 나오면 모든 자식 노드를 탐색해야 함(재귀적 검색) | ||
|
||
시간 복잡도: | ||
addWord: O(L) (L = 단어 길이) | ||
search: 최악의 경우 O(26^M) (M = 단어 길이, .이 연속된 경우) | ||
*검색할 단어가 모두 .로 구성된 경우 (예: ....) | ||
각 .에서 26개의 자식 노드를 모두 탐색해야 하므로 | ||
|
||
공간 복잡도: O(N) (N = 모든 단어의 총 문자 수) | ||
|
||
''' | ||
|
||
class TrieNode: | ||
def __init__(self): | ||
self.children = {} # 문자 -> 자식 노드에 저장 | ||
self.is_end = False # 단어 끝 표시 | ||
|
||
class WordDictionary: | ||
def __init__(self): | ||
self.root = TrieNode() | ||
|
||
# 단어를 문자별로 트라이에 추가 | ||
def addWord(self, word: str): | ||
node = self.root | ||
for char in word: | ||
if char not in node.children: | ||
node.children[char] = TrieNode() | ||
node = node.children[char] | ||
|
||
# 단어 끝 표시 | ||
node.is_end = True | ||
|
||
# 깊이 우선 탐색(dfs)함수로 재귀적 탐색. | ||
def search(self, word: str): | ||
def dfs(node, index): | ||
if index == len(word): | ||
return node.is_end | ||
char = word[index] | ||
# .이면 모든 자식 노드 탐색 | ||
if char != '.': | ||
return char in node.children and dfs(node.children[char], index+1) | ||
else: | ||
for child in node.children.values(): | ||
if dfs(child, index+1): | ||
return True | ||
return False | ||
|
||
return dfs(self.root, 0) | ||
|
||
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
''' | ||
이 문제는 주어진 정수 배열에서 가장 긴 증가하는 부분 수열(LIS)의 길이를 찾는 문제임 | ||
부분 수열이 연속되지는 않아도 되지만 순서는 유지해야 함 | ||
이진 탐색을 활용! | ||
|
||
시간 복잡도: O(n log n) | ||
각 숫자마다 이진 탐색(O(log n))을 수행하므로 전체 O(n log n) | ||
|
||
공간 복잡도: O(n) | ||
tails 배열이 최대 n의 공간을 사용함 | ||
|
||
|
||
Example 1의 경우를 들면 | ||
nums = [10,9,2,5,3,7,101,18] | ||
|
||
| 단계 | 처리할 숫자 | 동작 설명 | `tails` 배열 상태 | | ||
|------|-------------|----------------------------------|-----------------------| | ||
| 1 | 10 | 빈 배열에 10 추가 | `[10]` | | ||
| 2 | 9 | 10보다 작으므로 10 → 9로 교체 | `[9]` | | ||
| 3 | 2 | 9보다 작으므로 9 → 2로 교체 | `[2]` | | ||
| 4 | 5 | 2보다 크므로 5 추가 | `[2, 5]` | | ||
| 5 | 3 | 5보다 작으므로 5 → 3로 교체 | `[2, 3]` | | ||
| 6 | 7 | 3보다 크므로 7 추가 | `[2, 3, 7]` | | ||
| 7 | 101 | 7보다 크므로 101 추가 | `[2, 3, 7, 101]` | | ||
| 8 | 18 | 101보다 작으므로 101 → 18로 교체 | `[2, 3, 7, 18]` | | ||
|
||
최종 결과 : tails 배열의 길이 = 4 | ||
최장 증가 부분 수열 예시 : [2, 3, 7, 18] 또는 [2, 3, 7, 101] 등이 가능함 | ||
|
||
''' | ||
|
||
class Solution: | ||
def lengthOfLIS(self, nums: List[int]): | ||
|
||
# 각 길이의 부분 수열 중 가장 작은 마지막 값을 저장함 | ||
tails = [] | ||
|
||
for num in nums: | ||
|
||
# num이 들어갈 적절한 위치를 이진 탐색으로 찾음 | ||
index = bisect.bisect_left(tails, num) | ||
|
||
if index == len(tails): | ||
|
||
# num이 tails의 모든 값보다 크면 새로운 길이의 부분 수열을 생성 | ||
tails.append(num) | ||
else: | ||
|
||
# 기존 부분 수열의 마지막 값을 더 작은 num으로 갱신함 | ||
# tails 배열의 의미는 tails[i] = 길이가 i+1인 부분 수열의 가장 작은 마지막 값을 유지하여 | ||
# 새로운 숫자가 추가되기 쉬워짐 | ||
tails[index] = num | ||
|
||
# tails의 길이가 최대 LIS 길이임 | ||
return len(tails) | ||
|
||
|
||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 이진 탐색으로 찾는 방법이 있군요! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
''' | ||
주어진 2차원 행렬을 나선형 순서로 반환하는 문제임 | ||
조건 : 위->오른쪽->아래->왼쪽을 반복적으로 순회하며 범위를 좁혀감 | ||
|
||
Example 1. 의 경우 | ||
1 2 3 | ||
4 5 6 | ||
7 8 9 | ||
단계 | top bottom left right |현재 행렬 상태 | 동작 설명 | ||
시작 0 2 0 2 1 2 3 | ||
4 5 6 | ||
7 8 9 위쪽 행() 처리 후 top=1로 증가 | ||
|
||
2-1 1 2 0 2 . . . | ||
4 5 6 | ||
7 8 9 오른쪽 열(열 2)의 행 1 처리: 6 추가 | ||
|
||
2-2 1 2 0 2 . . . | ||
4 5 6 | ||
7 8 9 오른쪽 열(열 2)의 행 2 처리: 9 추가 | ||
|
||
끝 1 2 0 1 . . . | ||
4 5 6 | ||
7 8 9 오른쪽 열 처리 끝, right=1로 감소 | ||
|
||
|
||
''' | ||
|
||
|
||
class Solution: | ||
def spiralOrder(self, matrix: List[List[int]]): | ||
if not matrix: | ||
return [] | ||
|
||
result = [] | ||
top, bottom = 0, len(matrix) - 1 | ||
left, right = 0, len(matrix[0]) - 1 | ||
|
||
while top <= bottom and left <= right: | ||
|
||
# 위쪽 행을 왼쪽 → 오른쪽으로 순회 | ||
for i in range(left, right + 1): | ||
result.append(matrix[top][i]) | ||
|
||
# 다음부터 위쪽 행은 아래로 한 칸 이동 | ||
top += 1 | ||
|
||
# 오른쪽 열을 위쪽 → 아래쪽로 순회 | ||
for i in range(top, bottom + 1): | ||
result.append(matrix[i][right]) | ||
|
||
# 다음부터 오른쪽 열은 왼쪽으로 한 칸 이동 | ||
right -= 1 | ||
|
||
# 아래쪽 행을 오른쪽 → 왼쪽으로 순회(행이 남아있을 때만) | ||
if top <= bottom: | ||
for i in range(right, left - 1, -1): | ||
result.append(matrix[bottom][i]) | ||
bottom -= 1 | ||
|
||
# 열이 남아 있을 때만 왼쪽 열을 아래쪽 → 위쪽으로 순회 | ||
if left <= right: | ||
for i in range(bottom, top - 1, -1): | ||
result.append(matrix[i][left]) | ||
left += 1 | ||
|
||
return result | ||
|
||
|
||
|
||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
''' | ||
이 문제는 주어진 괄호 문자열 (), {}, []이 올바르게 닫혔는지 확인하는 문제임 | ||
|
||
조건 : 1) 같은 타입의 괄호로 닫혀야 함 | ||
2) 괄호가 올바른 '순서'로 닫혀야 함 | ||
3) 모든 닫는 괄호는 대응하는 여는 괄호가 있어야 함 | ||
|
||
해결방법 : 스택 자료 구조를 사용하여, 여는 괄호는 스택에 넣고, | ||
닫는 괄호가 나오면 스택의 마지막 요소와 짝이 맞는지 확인해야 함. | ||
|
||
예를 들어, s = "([)]" | ||
|
||
1. ( → 스택 추가 | ||
2. [ → 스택 추가 | ||
3. ) → 스택 마지막 [와 짝이 안 맞음 → False | ||
|
||
''' | ||
|
||
class Solution: | ||
def isValid(self, s: str): | ||
stack = [] | ||
# 닫는 괄호를 키로, 여는 괄호를 값으로 딕셔너리에 저장 | ||
pair = {')': '(', '}': '{', ']': '['} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 짝이 되는 괄호를 미리 배열로 만들어 두어서 코드가 더 가독성이 더 높아지는 것 같네요 |
||
|
||
for char in s: | ||
|
||
#char이 여는 괄호인지 확인 후 맞으면 스택에 추가 | ||
if char in pair.values(): | ||
stack.append(char) | ||
|
||
|
||
else: | ||
#스택이 비어 있으면 짝이 맞는 여는 괄호가 없음 | ||
#스택의 마지막 요소와 현재 닫는 괄호의 짝이 다르면 잘못된 문자열임 | ||
if not stack or pair[char] != stack.pop(): | ||
|
||
#모든 문자 처리 후 스택이 비어 있어야 올바른 문자열임 | ||
return False | ||
|
||
#스택이 비어있어야 모든 괄호가 닫힘 | ||
return not stack | ||
|
||
|
||
|
||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
역시 파이썬이 코드로 보기에는 java, c++ 보다 더 간결해서 코드 짜기가 수월하네요