Repository navigation
[Chaewon-Park-STUDY] WEEK 01 Solutions #2914
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
1a4b92a
351227d
bf814ae
fe2ab7a
286bd2a
af1ac83
20ed0c5
5556a08
4b765b4
4cc57c9
7b88b7d
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 @@ | ||
| class Solution: | ||
| def containsDuplicate(self, nums: list[int]) -> bool: | ||
| store = set() | ||
| # count를 쓰면 매번 전체 배열을 훑어 O(n^2) → Time out | ||
| # 대신 해시 기반 set을 쓰면 in 확인이 평균 O(1)이라 전체 O(n) | ||
| # Time: O(n), Space: O(n) | ||
| for elem in nums: | ||
| if elem in store: | ||
| return True | ||
| else: | ||
| store.add(elem) | ||
| return False | ||
|
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| class Solution: | ||
| def rob(self, nums: list[int]) -> int: | ||
| #시간, 공간 복잡도: O(n) | ||
| if len(nums)==1: | ||
| return nums[0] | ||
| elif len(nums)==2: | ||
| return max(nums) | ||
| dp=nums.copy() # dp[i] = i번째 집의 money를 훔칠 때의 최대 누적 금액 | ||
| for i in range(2,len(nums)): | ||
| house3 = dp[i-3] if i >= 3 else 0 #i=2일 경우에는 i-3이 존재하지 않기에 따로 처리 | ||
| dp[i] += max(dp[i-2], house3) #인접한 집은 방문 불가 | ||
| return max(dp) | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| class Solution: | ||
| def longestConsecutive(self, nums: list[int]) -> int: | ||
| if not nums: | ||
| return 0 | ||
| nums = sorted(set(nums)) # 처음에는 nums.sort()로 풀었지만 | ||
|
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. ❗ 저도 처음에는 sorted로 원소들을 정렬한 다음 푸는 방법을 사용했었는데요. 개선할 수 있는 방법이 있더라고요. 지금 풀이도 "오, 이렇게 생각할 수 있구나."라는 생각이 들었던 좋은 풀이라고 생각합니다! |
||
| # elif문에 중복 처리 부분을 넣어야해서 set으로 중복 허용 x | ||
| k=len(nums) | ||
|
|
||
| # Space: O(n), Time: O(n log n) - 정렬 O(n log n) + DP O(n) | ||
| dp=[1 for _ in range(k)] # dp[i] = nums[i]로 끝나는 연속 수열의 길이 | ||
| for i in range(1,k): | ||
| if nums[i]-nums[i-1]==1: | ||
| dp[i]=dp[i-1]+1 | ||
| return max(dp) | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| from collections import defaultdict #defaultdict 사용 위함 | ||
|
|
||
| class Solution: | ||
| def topKFrequent(self, nums: list[int], k: int) -> list[int]: | ||
| # 전체 시간 복잡도: O(n log n), 공간 복잡도: O(n) | ||
| output=[] | ||
| frequent=defaultdict(int) # 없는 key에 접근할시 0 생성 (리뷰 반영! ) | ||
|
|
||
| # count로 하면 전체를 다 훑기 때문에 O(n^2) | ||
| # dic 사용하여 공간 복잡도: O(n) | ||
| for elem in nums: | ||
| frequent[elem] +=1 # get 대신 | ||
| #정렬 시 시간복잡도 최대 O(nlogn) | ||
| result = dict(sorted(frequent.items(), key=lambda x: x[1], reverse=True)) #내림차순 정렬 | ||
|
|
||
| #빈도가 높은 원소 k개 추출: O(k) | ||
| for key in result: | ||
| output.append(key) | ||
| if len(output)==k: | ||
| return output | ||
| return output | ||
|
Comment on lines
+19
to
+21
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. 💬
Member
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. return output으로 바로 고치는 방향이 명확할 듯 하네요👍 |
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| class Solution: | ||
| #시간, 공간 복잡도:O(n) | ||
| def twoSum(self, nums: list[int], target: int) -> list[int]: | ||
| num_index={} #elem를 key로 바로 저장하여 시간복잡도 O(1) # 리뷰 후 수정!!: 기존에 arr로 선언하였는데 딕셔너리를 arr로 두면 변수명에 혼란이 있을 수 있기에 수정 | ||
| for i, elem in enumerate(nums): | ||
| if target -elem in num_index: #왜 num_index에서 찾는지 nums에서 찾으면 리스트라서 역시 복잡도 올라감 | ||
| # 두 수의 합이므로 나머지 짝이 num_index에 있는지 확인 | ||
| return [num_index[target - elem], i] | ||
| num_index[elem] = i #없으면 저장 | ||
|
|
||
|
|
||
|
|
||
|
|
||
| # 처음 시도 풀이 DFS(기각, runtime: 7013ms) | ||
| # 시간 복잡도: O(n^2), 공간 복잡도: O(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. 오, 저는 '1트에는 이렇게 풀었는데 틀렸다' 정도로만 적었는데,
Member
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. 저는 새로운 풀이를 완전히 내 것으로 체화하기까지 계속 같은 풀이만을 고수하는 습관이 있어서 ㅋ큐ㅠㅠ |
||
|
|
||
| # class Solution: | ||
| # def twoSum(self, nums: list[int], target: int) -> list[int]: | ||
| # arr = [] | ||
|
|
||
| # def dfs(start): | ||
| # if len(arr) == 2: | ||
| # return nums[arr[0]] + nums[arr[1]] == target #정답 발견시 True반환 | ||
| # for i in range(start, len(nums)): | ||
| # arr.append(i) | ||
| # if dfs(i + 1): # 정답이면 True를 위로 전달해 탐색 종료 | ||
| # return True | ||
| # arr.pop() | ||
| # return False | ||
|
|
||
| # dfs(0) | ||
| # return arr | ||
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.
👍 dp라는 배열에 index에 해당하는 집을 털었을 때 벌 수 있는 가장 큰 수익을 저장하는 용도로 사용하셨군요.
좋은 풀이 감사합니다.