-
-
Notifications
You must be signed in to change notification settings - Fork 195
[Chaedie] Week 3 #767
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
[Chaedie] Week 3 #767
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
2fc5ef0
feat: [Week 03-1] solve two-sum
Chaedie dc8c121
feat: [Week 03-2] solve reverse-bits
Chaedie 3d25456
feat: [Week 03-3] solve product-of-array-except-self
Chaedie c5b614d
feat: [Week 03-4] solve combination-sum
Chaedie 04b8deb
feat: [Week 03-5] solve maximum-subarray
Chaedie 1d9e0e1
Merge branch 'DaleStudy:main' into main
Chaedie 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,35 @@ | ||
""" | ||
Solution: | ||
최초 풀이 당시엔 단순히 dfs로 풀었으나 시간 초과로 실패했습니다. | ||
이후 풀이 설명을 통해 i 번째 숫자를 넣거나 / 안넣거나 라는 조건으로 i를 늘려가도록 진행하는 백트래킹을 하면 된다는점을 배웠습니다. | ||
이를 통해 불필요한 중복을 줄이고 효율적인 구현이 가능해집니다. | ||
|
||
C: len(candidates) | ||
T: target size | ||
|
||
Time: O(C^T) = 라고 설명되어 있는데 솔찍히 잘 모르겠습니다. | ||
Space: O(T) = 재귀가 가장 깊을 때 [1,1,1,1...] T 만큼이기 때문에 O(T) | ||
""" | ||
|
||
|
||
class Solution: | ||
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: | ||
result = [] | ||
sol = [] | ||
n = len(candidates) | ||
|
||
def backtrack(i, cur_sum): | ||
if cur_sum == target: | ||
result.append(sol.copy()) | ||
return | ||
if cur_sum > target or i == n: | ||
return | ||
|
||
backtrack(i + 1, cur_sum) | ||
|
||
sol.append(candidates[i]) | ||
backtrack(i, cur_sum + candidates[i]) | ||
sol.pop() | ||
|
||
backtrack(0, 0) | ||
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,64 @@ | ||
""" | ||
Solution1: | ||
sliding window 일 것 같지만 구현이 어려워 일단 Brute Force 부터 진행합니다. | ||
-> 시간 초과로 실패 | ||
|
||
Time: O(n^2) = n(for) * n(for) | ||
Space: O(n) = cur 배열 | ||
""" | ||
|
||
|
||
class Solution: | ||
def maxSubArray(self, nums: List[int]) -> int: | ||
n = len(nums) | ||
max_sum = float(-inf) | ||
for i in range(n): | ||
cur = [] | ||
cur_sum = 0 | ||
for j in range(i, n): | ||
cur_sum += nums[j] | ||
cur.append(nums[j]) | ||
max_sum = max(max_sum, cur_sum) | ||
return max_sum | ||
|
||
|
||
""" | ||
Solution2: | ||
Sliding Window로 풀 수 있을거라 생각했는데 잘 안되었습니다. | ||
""" | ||
|
||
|
||
class Solution: | ||
def maxSubArray(self, nums: List[int]) -> int: | ||
n = len(nums) | ||
max_sum = float(-inf) | ||
|
||
l = 0 | ||
window = 0 | ||
for r in range(n): | ||
window += nums[r] | ||
max_sum = max(max_sum, window) | ||
while max_sum < window: | ||
l += 1 | ||
|
||
return max_sum | ||
|
||
|
||
""" | ||
Solution3 - 알고달레: | ||
솔루션을 통해 학습했습니다. | ||
이해가 어려워 다시 풀어볼 예정입니다. | ||
|
||
Time: O(n) | ||
Space: O(1) | ||
""" | ||
|
||
|
||
class Solution: | ||
def maxSubArray(self, nums: List[int]) -> int: | ||
max_sum = nums[0] | ||
cur_sum = 0 | ||
for num in nums: | ||
cur_sum = max(cur_sum + num, num) | ||
max_sum = max(cur_sum, max_sum) | ||
return max_sum |
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,65 @@ | ||
""" | ||
solution 1: | ||
왼쪽부터 곱해가는 prefix, | ||
오른쪽부터 곱해가는 postfix, | ||
2가지의 배열을 만든다. | ||
|
||
nums = [1,2,3,4] | ||
prefix = [1,2,6,24] | ||
postfix = [24,12,4,1] | ||
|
||
이후 정답 배열 result[i] = prefix[i - 1] * postfix[i + 1] 이 되도록 만든다. | ||
0, n-1 번째 인덱스에선 예외처리를 해준다. | ||
|
||
Time: O(n) = prefix 계산 O(n) + postfix 계산 O(n) + result 계산 O(n) | ||
Space: O(n) = prefix 배열 O(n) + postfix 배열 O(n) | ||
""" | ||
|
||
# class Solution: | ||
# def productExceptSelf(self, nums: List[int]) -> List[int]: | ||
# n = len(nums) | ||
|
||
# prefix = [1 for i in range(n)] | ||
# postfix = [1 for i in range(n)] | ||
|
||
# prefix[0] = nums[0] | ||
# for i in range(1, n): | ||
# prefix[i] = prefix[i-1] * nums[i] | ||
|
||
# postfix[n - 1] = nums[n - 1] | ||
# for i in range(n-2, -1, -1): | ||
# postfix[i] = postfix[i + 1] * nums[i] | ||
|
||
# result = [] | ||
# for i in range(n): | ||
# pre = prefix[i - 1] if i - 1 >= 0 else 1 | ||
# post = postfix[i + 1] if i + 1 < n else 1 | ||
# result.append(pre * post) | ||
# return result | ||
|
||
""" | ||
최적화 풀이 | ||
Solution: | ||
prefix, postfix 배열 저장 없이 순회하며 바로 prefix, postfix 를 곱해서 result 배열에 담는다. | ||
|
||
Time: O(n) = O(2n) | ||
Space: O(1) | ||
""" | ||
|
||
|
||
class Solution: | ||
def productExceptSelf(self, nums: List[int]) -> List[int]: | ||
n = len(nums) | ||
result = [1] * n | ||
|
||
prefix = 1 | ||
for i in range(n): | ||
result[i] *= prefix | ||
prefix *= nums[i] | ||
|
||
postfix = 1 | ||
for i in range(n - 1, -1, -1): | ||
result[i] *= postfix | ||
postfix *= nums[i] | ||
|
||
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,50 @@ | ||
""" | ||
1. 학습은 진행했지만, 스스로 완벽하게 풀지 못했습니다. | ||
다음주에 bit 연산으로 다시 풀어볼 예정입니다. | ||
""" | ||
|
||
|
||
class Solution: | ||
|
||
# 알고달레 풀이 1) Stack | ||
def reverseBits(self, n: int) -> int: | ||
stack = [] | ||
while len(stack) < 32: | ||
stack.append(n % 2) | ||
n //= 2 | ||
|
||
result, scale = 0, 1 | ||
while stack: | ||
result += stack.pop() * scale | ||
scale *= 2 | ||
return result | ||
|
||
# 알고달레 풀이 2) bit manipulation | ||
def reverseBits(self, n: int) -> int: | ||
result = 0 | ||
print(n) | ||
for i in range(32): | ||
print(result) | ||
result <<= 1 | ||
result |= n & 1 | ||
n >>= 1 | ||
return result | ||
|
||
# NeetCode 풀이 | ||
def reverseBits(self, n: int) -> int: | ||
res = 0 | ||
|
||
for i in range(32): | ||
bit = (n >> i) & 1 | ||
res = res | (bit << (31 - i)) | ||
return res | ||
|
||
# 스스로 풀기 | ||
# 한번 더 풀 에정입니다. | ||
def reverseBits(self, n: int) -> int: | ||
result = 0 | ||
for i in range(32): | ||
result = result << 1 | ||
result = result | (n & 1) | ||
n = n >> 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,21 @@ | ||
""" | ||
Solution: | ||
Use a hash map to store numbers and their indices | ||
Iterate through the list and check if difference between target and val | ||
return the index list | ||
|
||
Time: O(n) | ||
Space: O(n) | ||
|
||
""" | ||
|
||
|
||
class Solution: | ||
def twoSum(self, nums: List[int], target: int) -> List[int]: | ||
num_map = {} # num : index | ||
|
||
for i, val in enumerate(nums): | ||
diff = target - val | ||
if diff in num_map: | ||
return [num_map[diff], i] | ||
num_map[val] = i | ||
Comment on lines
+13
to
+21
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. 저는 이중 반복문으로 문제를 풀어서 시간 복잡도가 O(n²)�였는데, 해시맵을 사용하면 시간 복잡도를 줄일 수 있다는 걸 알게 되었습니다! 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. 브루트 포스 -> sort -> hash map 등등 다양한 풀이가 있더라구요. 감사합니다. |
Oops, something went wrong.
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.
저는 string manipulation을 이용해서 문제를 풀었는데, 비트 연산을 이용한 다양한 풀이방법을 배울 수 있었습니다!
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.
감사합니다..! 문제의 취지가 "비트 연산 사용해보기"인것 같아서 비트 위주로 풀어보았습니다..!