-
-
Notifications
You must be signed in to change notification settings - Fork 247
[wozlsla] WEEK 01 solutions #1715
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
3 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,3 @@ | ||
class Solution: | ||
def containsDuplicate(self, nums: List[int]) -> bool: | ||
return len(nums) > len(set(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,64 @@ | ||
class Solution: | ||
def longestConsecutive(self, nums: List[int]) -> int: | ||
|
||
# Edge case | ||
if not nums: | ||
return 0 | ||
|
||
# 1. HashSet | ||
table = set(nums) | ||
|
||
logest_seq = 0 | ||
|
||
# 2. 연속 시퀀스의 시작점 탐색 | ||
for num in table: | ||
if (num - 1) not in table: # !! | ||
current_num = num | ||
seq = 1 | ||
|
||
# 시퀀스 확장 | ||
while (current_num + 1) in table: | ||
current_num += 1 | ||
seq += 1 | ||
|
||
# 시퀀스 길이 업데이트 | ||
logest_seq = max(logest_seq, seq) | ||
|
||
return logest_seq | ||
|
||
|
||
""" | ||
Time complexity : O(N) | ||
- step 1 (iteration) : O(N) | ||
- 모든 숫자를 해시셋(set)에 저장 | ||
- 해시셋 사용 이유 : 중복을 제거하고 O(1) 탐색 가능 | ||
- 요소의 추가, 삭제, 존재 여부 확인에 평균적으로 O(1) 시간이 걸리는 자료구조 | ||
- 이 성질 덕분에 하단의 풀이가 간단해질 수 있음 | ||
- step 2 (iteration) : O(N) | ||
- 각 요소는 for, while 에서 최대 두번 처리됨 | ||
|
||
Space Complexity) | ||
- 해시셋(딕셔너리): O(N) (최악의 경우, 모든 숫자가 고유할 때) | ||
""" | ||
|
||
|
||
""" 첫번째 풀이 | ||
- 시간복잡도 고려 X. O(NlogN) | ||
- Edge case 대응 필요 | ||
- 연속된 요소 시퀀스가 하나가 아닐 경우 고려 필요 | ||
|
||
class Solution: | ||
def longestConsecutive(self, nums: List[int]) -> int: | ||
|
||
nums.sort() # 오름차순 | ||
|
||
cnt = 1 | ||
tmp = nums[0] | ||
|
||
for i in range(1, len(nums)): | ||
if nums[i] == tmp + 1: | ||
cnt += 1 | ||
tmp = nums[i] | ||
|
||
return cnt | ||
""" |
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,49 @@ | ||
import heapq | ||
|
||
|
||
class Solution: | ||
def topKFrequent(self, nums: List[int], k: int) -> List[int]: | ||
|
||
table = {} # 1. Initialize | ||
|
||
# 2. Populate frequency map | ||
for i in range(len(nums)): | ||
table[nums[i]] = table.get(nums[i], 0) + 1 | ||
|
||
# 3. Find top K frequent elements | ||
topk = heapq.nlargest(k, table, key=table.get) | ||
return topk | ||
|
||
|
||
""" | ||
* 초기 아이디어 * | ||
- 하나씩 전부 돌면서 빈도수 저장, k개 만큼만 -> 비교/정렬 과정 고려 필요 | ||
- count 함수를 써서 비교후 저장 -> 더 많은 반복? O | ||
- 일단 한번은 다 돌아야함. 가장 적게 돌 수 있는 방법? | ||
- 전체 순차 비교? | ||
- Counter, 빈도수 + top K개 | ||
|
||
Time complexity : O(N + MlogK) | ||
- step 2 (iteration) : O(N) | ||
- 리스트의 길이가 N 일때, nums 모두 순회 | ||
- step 3 (iteration) : O(NlogK) | ||
- heapq.nlargest 함수는 table의 모든 M개의 요소(키-값 쌍)를 순회하며, 크기 k의 최소 힙을 유지 | ||
- 힙에 삽입(or 제거 후 삽입) 연산은 힙의 크기 k에 비례, O(logK) | ||
- 각 요소에 적용 O(MlogK), 최악의 경우 O(NlogK). M은 N을 초과할 수 없음. | ||
|
||
Space Complexity) | ||
- 빈도수 맵 (딕셔너리): O(N) (최악의 경우, 모든 숫자가 고유할 때) | ||
- 힙 (heapq.nlargest 내부에서 사용): O(K) | ||
|
||
* heapq.nlargest * | ||
- 가장 큰 k개의 요소를 찾는 함수 | ||
1. 힙 초기화. 크기가 k인 (최소)힙 생성 | ||
2. 순회 및 힙 관리 | ||
- table 전체를 순회하며 key=table.get 값을 기준으로 비교 | ||
- 힙이 k개 미만일 경우 요소 추가, 다 찼을경우 비교후 재정렬 | ||
- 현재 요소 b의 값과 힙의 루트에 있는 요소 a를 비교 | ||
- b > a 이면, a를 제거하고 b를 추가 및 재정렬 | ||
- b <= a 이면, b를 버림 | ||
- 힙에 있는 요소들을 정렬된 리스트로 반환 | ||
- max heap이 아닌 min heap을 사용하는 이유 | ||
""" |
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,9 @@ | ||
class Solution: | ||
def twoSum(self, nums: List[int], target: int) -> List[int]: | ||
# idx를 따로 저장해두는 게 좋을까? X -> i를 사용하면 될듯 | ||
# 만약, 거꾸로 계산한다면? | ||
|
||
for i in range(len(nums) - 1): | ||
for j in range(i + 1, len(nums)): | ||
if nums[i] + nums[j] == target: | ||
return [i, j] |
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.
Uh oh!
There was an error while loading. Please reload this page.