Repository navigation
[201411108] WEEK 01 Solutions #2915
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
9b63b0e
ded8228
dd45385
9708e21
4ad0b22
4685391
c0c64c9
fa037b8
2f58ef3
9595fb7
1008056
a25cdb4
41b41a0
bb743b0
5fd0e38
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,13 @@ | ||
| # TC: O(n), nums의 원소를 하나씩 확인하기 때문에 O(n), 첫 두 원소가 같다면 O(1) | ||
| # set() 메서드는 C언어로 처리하기 때문에 실제 leetcode 제출 상 속도는 set을 활용한 경우 12ms, 첫 원소 확인 코드를 넣을 경우 16ms | ||
| # set 메서드를 쓰는 코드가 가독성이 좋다 판단하여 코드 수정 | ||
| # SC: O(n), 최악의 경우 n개의 원소가 set에 들어갈 수 있기 때문에 O(n) | ||
| class Solution: | ||
| def containsDuplicate(self, nums: list[int]) -> bool: | ||
| numsSet = set(nums) | ||
|
|
||
| if (len(numsSet) == len(nums)): | ||
| return False | ||
|
|
||
| return True | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| # TC: O(n), nums의 원소를 하나씩 확인 | ||
| # SC: O(n), 원소 갯수만큼 메모이제이션 배열 | ||
| class Solution: | ||
| def rob(self, nums: list[int]) -> int: | ||
| memo = [None] * len(nums) | ||
|
|
||
| def explore(idx: int) -> int: | ||
| if (idx >= len(nums)): | ||
| return 0 | ||
|
|
||
| if (memo[idx] is not None): | ||
| return memo[idx] | ||
|
|
||
| rob_current = nums[idx] + explore(idx + 2) | ||
| skip_current = explore(idx + 1) | ||
| memo[idx] = max(rob_current, skip_current) | ||
|
Comment on lines
+14
to
+16
Member
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[i]를 i번째 집을 반드시 방문할때 최대로 정의해서 bottom up 방식으로 풀었는데, @201411108님 풀이를 보면 변수명이 명확하다는 게 단번에 느껴집니다 저는 재귀를 쓸 때 recursionerror가 언제 발생할까 고민하는데, 어떤 경우에 재귀를 쓰시고 어떤 경우에 bottom-up을 쓰시는지 기준이 궁금합니다!
Contributor
Author
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. 코멘트 감사드립니다! 저도 사실 알고리즘을 다시 잡은지 얼마 되지 않아 어떨 때 재귀함수를 써야하고, 어떤 경우에 bottom up으로 타뷸레이션을 써야할지 경험을 많이 해야한다고 생각하고 있어요. functional programming 관점으로 생각하는 연습을 많이 하고 있는데요. FP 관점으로 생각했을 때 재귀함수가 적합하다 생각하여 재귀가 가능한 경우 어떻게 쓸지에 대해 고민을 하게 되는 것 같습니다. 이번 문제의 경우, 종료 조건이 명확했기 때문에 재귀함수로 작성해야겠다는 생각이 들었던 것 같아요. 사견입니다만, 알고리즘 문제의 꽤 많은 부분은 문제에서 어떤 문제 해결 방식을 써야 하는지에 대한 힌트를 담고 있다고 생각해요. 역설적으로 AI로 인해 해결 자체는 쉬워진 요즘에 오히려 문제를 어떻게 해결할지 방향을 잡아야 한다고 생각하는데 오히려 알고리즘 문제 해결이 도움이 많이 된다고 생각합니다. 이런 부분에서 다양한 접근법을 많이 공유할 수 있으면 좋을 것 같아요!
Member
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. 좋은 인사이트 감사합니다 :) |
||
| return memo[idx] | ||
|
|
||
| return explore(0) | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| # TC: O(n), set의 원소를 하나씩 확인하기 때문에 O(n) | ||
| # SC : O(n), 최대 n개의 원소가 set에 들어갈 수 있기 때문에 O(n) | ||
| class Solution: | ||
| def longestConsecutive(self, nums: list[int]) -> int: | ||
| nums_set = set(nums) | ||
| max_len = 0 | ||
|
|
||
| for num in nums_set: | ||
| if num - 1 in nums_set: # 이전 숫자가 존재하는(연속 시작점이 있는) 경우에는 continue | ||
|
Member
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. 제 풀이에 리뷰 달아주신 부분에 대한 코멘트를 읽어보다가 여기로 넘어오게 되었네요 ㅎㅎ 시작점이 아니면 continue를 하고 |
||
| continue | ||
|
|
||
| acc = 1 | ||
| while num + acc in nums_set: | ||
| acc += 1 | ||
|
|
||
| max_len = max(max_len, acc) | ||
|
|
||
| return max_len | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| # n : nums의 길이, m : 고유한 숫자의 개수 | ||
| # TC(n), 버킷 정렬에서 n + m 개를 조회하기 때문에 O(n + m) = O(n)이다. (m <= 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. 버킷을 이용하면 O(n) 에 끝낼 수 있군요!! |
||
| # SC(n) | ||
| # - dictionary O(m) | ||
| # - buckets O(n + 1 + m), 버킷의 수는 n + 1개, 내부에 저장된 숫자는 m개 | ||
| # - result O(k) | ||
| # - O(m + n + k)에서 k <= m <= n이므로 O(n) | ||
| from collections import defaultdict | ||
|
|
||
| class Solution: | ||
| def topKFrequent(self, nums: list[int], k: int) -> list[int]: | ||
| dictionary = defaultdict(int) | ||
|
|
||
| for num in nums: | ||
| if num in dictionary: | ||
| dictionary[num] += 1 | ||
| else: | ||
| dictionary[num] = 1 | ||
|
|
||
| buckets = [[] for _ in range(len(nums) + 1)] | ||
|
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. (제 이해를 돕고자 추가해둡니당) |
||
|
|
||
| for num, freq in dictionary.items(): | ||
| buckets[freq].append(num) | ||
|
|
||
| result = [] | ||
|
|
||
| # 인덱스가 등장 빈도를 의미하기 때문에 역순으로 조회 | ||
| for i in range(len(nums), 0, -1): | ||
| for num in buckets[i]: | ||
| result.append(num) | ||
| if len(result) == k: | ||
| return result | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| # TC: O(n) | ||
| # SC: O(n) | ||
| from collections import defaultdict | ||
|
|
||
| class Solution: | ||
| def twoSum(self, nums: list[int], target: int) -> list[int]: | ||
| dictionary = defaultdict(int) | ||
|
|
||
| for i, num in enumerate(nums): | ||
| diff = target - num | ||
| if diff in dictionary and i != dictionary[diff]: | ||
| return [i, dictionary[diff]] | ||
| dictionary[num] = i | ||
|
Comment on lines
+3
to
+13
Member
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. 안녕하세요 :) 말씀해 주신 defaultdict 요긴하게 활용하고 있습니다. |
||
|
|
||
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.
파이썬 코드는 낯선데, 생각의 흐름이 잘보여서 따라가기 좋네요ㅎㅎ 👍