-
-
Notifications
You must be signed in to change notification settings - Fork 361
[freemjstudio] WEEK 02 Solutions #2703
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
base: main
Are you sure you want to change the base?
Changes from all commits
865ed8d
1a6de37
9531176
370fe38
db69654
4886e4a
2f3e189
4c68b30
22f9365
dae40c7
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| class Solution: | ||
| def threeSum(self, nums: list[int]) -> list[list[int]]: | ||
| answer = [] | ||
| nums.sort() | ||
|
|
||
| for i in range(len(nums)): | ||
| # 중복된 원소가 있는 경우 똑같이 검사할 필요가 없으므로 건너뛴다. | ||
| if i > 0 and nums[i] == nums[i-1]: | ||
| continue | ||
|
|
||
| left, right = i+1, len(nums) - 1 | ||
|
|
||
| while left < right: | ||
| total = nums[i] + nums[left] + nums[right] | ||
| if total == 0: | ||
| answer.append([nums[i], nums[left], nums[right]]) | ||
| # left, right 포인터를 둘다 한칸씩 이동시켜 다음 조합을 검사한다. | ||
| left += 1 | ||
| right -= 1 | ||
|
|
||
| # 중복된 원소가 있는 경우 같은 정답 조합을 방지한다 | ||
| while left < right and nums[left] == nums[left -1]: | ||
| left += 1 | ||
|
|
||
| elif total < 0: | ||
| left += 1 | ||
| else: | ||
| right -= 1 | ||
| return answer |
|
Contributor
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. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 상수 크기의 배열 dp를 사용해 결과를 누적한다. 초기 경계 처리와 인덱스 사용이 명확합니다. 개선 제안: 필요하다면 공간을 O(1)로 줄일 수 있습니다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| class Solution: | ||
| def climbStairs(self, n: int) -> int: | ||
| answer = 0 | ||
| if n == 1: # ways(1) = 1 | ||
| return 1 | ||
|
|
||
| if n == 2: # ways(2) = 2 | ||
| return 2 | ||
|
|
||
| dp = [0] * 46 # 1 <= n <= 45 | ||
| dp[1] = 1 | ||
| dp[2] = 2 | ||
|
|
||
| # 점화식 : ways(n) = ways(n-1) + ways(n-2) | ||
| for i in range(3, n+1): | ||
| dp[i] = dp[i-1] + dp[i-2] | ||
| return dp[n] |
|
Contributor
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. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 집합을 사용해 중복 여부를 판정하는 일반적인 방법이지만 주석에서 상수 시간으로 길이를 얻는 부분은 구현 의도가 불분명합니다. 개선 제안: Set 사용으로 간결하게 작성되어 좋지만, first 변수를 제거하고 set의 크기 비교로 표현해도 명확합니다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| class Solution: | ||
| def containsDuplicate(self, nums: List[int]) -> bool: | ||
| first = len(nums) # O(1) : 리스트 객체는 이미 자기자신의 길이를 저장하고 있음 | ||
| set_nums = set(nums) # O(N) | ||
| second = len(set_nums) | ||
| return (first != second) | ||
|
|
||
| # 시간 복잡도 : O(N) |
|
Contributor
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. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 빈도 계산과 힙을 이용해 시간과 공간을 효율적으로 관리합니다. k가 작으면 성능이 좋고, 해시맵과 힙의 조합이 적절합니다. 개선 제안: 추출 시 힙에서 꺼낸 순서를 정렬해 반환하면 더 안정적일 수 있습니다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| import heapq | ||
|
|
||
| class Solution: | ||
| def topKFrequent(self, nums: List[int], k: int) -> List[int]: | ||
| answer = [] | ||
| count = dict() | ||
| heap = [] | ||
| if len(nums) <= 1: | ||
| return nums | ||
| # O(N) | ||
| for num in nums: | ||
| count[num] = count.get(num, 0) + 1 | ||
|
|
||
| # heap 의 크기는 최대 k 로 제한함. | ||
| # unique 한 M개의 숫자를 선형 순회 O(M) | ||
| for num, freq in count.items(): | ||
| if len(heap) < k: | ||
| heapq.heappush(heap, (freq, num)) # O(logK) | ||
| else: | ||
| if heap[0][0] < freq: | ||
| heapq.heappop(heap) # O(logK) | ||
| heapq.heappush(heap, (freq, num)) # O(logK) | ||
|
|
||
| for _ in range(k): | ||
| k, v = heapq.heappop(heap) | ||
| answer.append(v) | ||
|
|
||
| return answer | ||
|
|
|
Contributor
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. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 한 번의 순회로 해답을 찾는 전형적인 해시맵 풀이입니다. 개선 제안: 정답이 여러 개인 경우의 처리나 예외 상황에 대한 테스트를 보강하면 좋습니다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| class Solution: | ||
| def twoSum(self, nums: List[int], target: int) -> List[int]: | ||
| answer = [] | ||
| hashmap = dict() | ||
| for i in range(len(nums)): | ||
| current_num = nums[i] | ||
| diff = target - current_num | ||
| if diff in hashmap.keys(): | ||
| return [i, hashmap[diff]] | ||
| hashmap[current_num] = i # store the index of current num | ||
|
|
||
| return answer |
|
Contributor
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. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 두 가지 풀이가 제시되어 있습니다. 두 번째 풀이가 일반적으로 더 좋은 최악의 시간복잡도를 가집니다. 개선 제안: 두 풀이를 중복으로 선언하기보단 하나의 선택된 구현으로 일관되게 유지하는 편이 좋습니다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| """ | ||
| 첫번째 풀이 | ||
| 시간 복잡도 : O(n log n) | ||
| """ | ||
|
|
||
| class Solution: | ||
| def isAnagram(self, s: str, t: str) -> bool: | ||
| return sorted(s) == sorted(t) | ||
|
|
||
| """ | ||
| 두번째 풀이 | ||
| 시간 복잡도 : O(n) | ||
| """ | ||
|
|
||
| class Solution: | ||
| def isAnagram(self, s: str, t: str) -> bool: | ||
| # 반례 : s = ab, t = a | ||
| # 이 경우에는 t에 없는 b가 존재하므로 False를 반환해야 한다. | ||
| if len(s) != len(t): | ||
| return False | ||
| counter = {} | ||
|
|
||
| for ch in s: | ||
| counter[ch] = counter.get(ch, 0) + 1 | ||
|
|
||
| for ch in t: | ||
| if ch not in counter: | ||
| return False | ||
| counter[ch] -= 1 | ||
| if counter[ch] < 0: | ||
| return False | ||
| return True |
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.
🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 정렬과 두 포인터를 이용해 중복 제거 로직이 포함되어 있어 시간복잡도는 O(n^2)이며 공간은 입력 배열 외 추가 공간이 거의 필요없습니다.
개선 제안: 현재 구현이 적절해 보입니다.