-
-
Notifications
You must be signed in to change notification settings - Fork 338
[riveroverflows] WEEK 01 Solutions #2362
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
4 commits
Select commit
Hold shift + click to select a range
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,22 @@ | ||
| from typing import List | ||
|
|
||
|
|
||
| class Solution: | ||
| """ | ||
| 풀이: | ||
| - nums를 set으로 변환하면 중복이 제거된다. | ||
| - set의 길이와 원본 리스트의 길이가 다르면 중복이 존재한다는 뜻. | ||
|
|
||
| TC: O(n) | ||
| - set(nums): 리스트의 모든 원소를 순회하면서 set에 삽입. O(n) | ||
| - set 삽입은 해시 기반이라 평균 O(1), n개 원소니까 O(n) | ||
| - len(set(nums)): set의 길이 조회. O(1) | ||
| - len(nums): 리스트의 길이 조회. O(1) | ||
| - 종합: O(n) + O(1) + O(1) = O(n) | ||
|
|
||
| SC: O(n) | ||
| - set(nums): 중복이 없는 경우 최대 n개의 원소를 저장. O(n) | ||
| - 그 외 변수 없음 | ||
| """ | ||
| def containsDuplicate(self, nums: List[int]) -> bool: | ||
| return len(set(nums)) != len(nums) |
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,46 @@ | ||
| from typing import List | ||
|
|
||
|
|
||
| class Solution: | ||
| """ | ||
| TC: O(n), SC: O(n) | ||
|
|
||
| n은 nums 리스트의 길이. | ||
|
|
||
| 풀이과정: | ||
| - nums를 set으로 만드는 것까진 알겠는데 이후로 풀이가 이어지지 않았음 | ||
| - 여러 풀이 방법을 시도해보다가 도저히 생각나지 않아서 LeetSub 플러그인 힌트 4/5까지 봄 | ||
| - "num - 1이 set에 없다면 sequence의 시작 숫자일 수 있다"에서 힌트를 얻어서 풀게 됨 | ||
|
|
||
| 풀이: | ||
| - set에 넣어서 O(1) 조회할 수 있도록 함 | ||
| - set에 num-1 값이 있다면 num은 sequence의 시작 숫자가 아니므로 skip | ||
| - 시작 숫자에서 cnt(+1, +2, +3, ...)를 더해가며 set에 있는지 확인 | ||
| - answer와 cnt 중 더 큰 값을 answer에 저장 | ||
|
|
||
| TC: | ||
| - set(nums): n개 원소 삽입. O(n). | ||
| - for num in nums_set: set 전체 순회. O(n). | ||
| - if num - 1 in nums_set: 해시 기반 조회. O(1). | ||
| - while: 시작 숫자에서만 실행. for-while 중첩이라 O(n²)처럼 보이지만, | ||
| 각 원소는 while에서 최대 1번만 방문됨. 전체 while 반복 합계 = O(n). | ||
| - 종합: O(n). | ||
|
|
||
| SC: | ||
| - nums_set: 최악 n개 원소. O(n). | ||
| - answer, cnt: 상수. O(1). | ||
| - 종합: O(n). | ||
| """ | ||
| def longestConsecutive(self, nums: List[int]) -> int: | ||
| nums_set = set(nums) | ||
| answer = 0 | ||
|
|
||
| for num in nums_set: | ||
| if num - 1 in nums_set: | ||
| continue | ||
| cnt = 0 | ||
| while num + cnt in nums_set: | ||
| cnt += 1 | ||
| answer = max(answer, cnt) | ||
|
|
||
| return answer |
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 @@ | ||
| from typing import List | ||
|
|
||
|
|
||
| class Solution: | ||
| """ | ||
| 풀이: | ||
| - 빈도수 세기 + Bucket Sort를 조합해서 정렬 없이 O(n)에 상위 k개를 뽑는다. | ||
| - 1단계: nums를 순회하며 각 숫자의 등장 횟수를 dict로 센다. | ||
| - 2단계: 빈도수를 인덱스로 하는 버킷 배열을 만든다. | ||
| 빈도수는 최대 len(nums)이므로 배열 크기가 고정됨. | ||
| - 3단계: 버킷 배열을 뒤에서부터(높은 빈도수부터) 순회하며 k개를 수집한다. | ||
| - 정렬(O(n log n)) 대신 버킷의 인덱스 자체가 정렬 역할을 하므로 O(n). | ||
|
|
||
| TC: O(n) | ||
| - 빈도수 세기: nums를 한 번 순회. O(n). | ||
| - 버킷 배열 생성: 고유 원소 수만큼 순회. 최악 O(n). | ||
| - 상위 k개 수집: 버킷 배열을 뒤에서부터 순회. 최악 O(n). | ||
| - 종합: O(n). | ||
|
|
||
| SC: O(n) | ||
| - counts(dict): 최악 n개의 고유 원소. O(n). | ||
| - bucket(list of lists): 크기 n+1. O(n). | ||
| - answer(list): 최대 k개. O(k) ≤ O(n). | ||
| - 종합: O(n). | ||
| """ | ||
| def topKFrequent(self, nums: List[int], k: int) -> List[int]: | ||
| counts = dict() | ||
| for num in nums: | ||
| if num not in counts: | ||
| counts[num] = 0 | ||
| counts[num] += 1 | ||
|
|
||
| bucket = [[] for _ in range(len(nums) + 1)] | ||
| for num, cnt in counts.items(): | ||
| bucket[cnt].append(num) | ||
|
|
||
| answer = [] | ||
| for cnt_list in reversed(bucket): | ||
| if not cnt_list: | ||
| continue | ||
| for num in cnt_list: | ||
| answer.append(num) | ||
| if len(answer) == k: | ||
| return answer | ||
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 @@ | ||
| from typing import List | ||
|
|
||
|
|
||
| class Solution: | ||
| """ | ||
| 풀이: | ||
| - 배열을 한 번 순회하면서, 각 숫자에 대해 | ||
| "나와 더해서 target이 되는 짝(complement)"이 | ||
| 이미 등장했는지를 dict로 확인한다. | ||
| - dict에 {숫자: 인덱스}를 저장해두면, complement 조회가 O(1)이므로 전체 O(n). | ||
| - complement를 먼저 확인하고, 그 다음에 현재 숫자를 | ||
| dict에 넣기 때문에 같은 값이 두 번 나오는 경우 | ||
| (예: [3,3], target=6)에도 정상 동작한다. | ||
|
|
||
| TC: O(n) | ||
| - for 루프: nums의 모든 원소를 최대 한 번 순회. O(n) | ||
| - complement 계산 (target - num): O(1) | ||
| - dict에서 complement 존재 여부 확인 (in 연산): 해시 기반이라 평균 O(1) | ||
| - dict에 현재 숫자 삽입: 평균 O(1) | ||
| - 최악의 경우(답이 마지막 쌍): n번 반복. 최선의 경우(답이 첫 두 원소): 2번 반복 | ||
|
|
||
| SC: O(n) | ||
| - nummap(dict): 최악의 경우 n-1개의 원소를 저장 (마지막 원소 직전까지 다 넣음). O(n) | ||
| - complement, i, num: 입력 크기와 무관한 상수. O(1) | ||
| """ | ||
| def twoSum(self, nums: List[int], target: int) -> List[int]: | ||
| nummap = dict() | ||
|
|
||
| for i, num in enumerate(nums): | ||
| complement = target - num | ||
|
|
||
| if complement in nummap: | ||
| return [nummap[complement], i] | ||
|
|
||
| nummap[num] = i |
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.
이 부분을 Counter 을 사용하면 더 간결하게 작성할 수 있을것 같습니다~
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/kotlin인데python으로만 문제를 풀다보니 주언어로는 전혀 못 풀겠더라구요그래서 최대한 풀어서 작성해보는 연습을 하고 있었습니다 ㅎㅎ
리뷰 감사합니다!