-
-
Notifications
You must be signed in to change notification settings - Fork 195
[KwonNayeon] Week 1 #656
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
[KwonNayeon] Week 1 #656
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
8cc191c
Add placeholder file for 'Contains Duplicate' problem
KwonNayeon abc84fc
Add solution for "217. Contains Duplicate"
KwonNayeon c8199c9
Add newline at the end of the file to comply with the CI requirements
KwonNayeon 6344174
Add solution for Valid Palindrome problem
KwonNayeon 365c1cc
Update description and conditions for Valid Palindrome problem
KwonNayeon 5212548
Solved 237. Top K Frequent Elements problem
KwonNayeon 228f63b
Add newline at the end of the file to comply with the CI requirements
KwonNayeon a4fa1ea
Fix: remove unnecessary spaces before newline to comply with CI requi…
KwonNayeon f7ae499
Solved 128. Longest Consecutive Sequence problem
KwonNayeon 65c2c59
Solved 198. House Robber using Python code
KwonNayeon dd6ca48
refactor: Improve time complexity using heap for topKFrequent
KwonNayeon dfb6f0c
Fix: Include numeric characters in palindrome check
KwonNayeon a211d72
Fix: Updated isPalindrome function to return true/false.
KwonNayeon 2173819
Add placeholder file for 'Valid Anagram' problem
KwonNayeon 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,39 @@ | ||
""" | ||
Title: 217. Contains Duplicate | ||
Link: https://leetcode.com/problems/contains-duplicate/ | ||
|
||
Summary: | ||
- 주어진 배열 `nums`에서 어떤 값이 한 번 이상 등장하면 True를 반환하고, 배열의 모든 값이 유일한 경우에는 False를 반환함 | ||
- Input: `nums = [1,2,3,1]` | ||
- Output: `True` | ||
|
||
Conditions: | ||
- 중복이 있으면: 배열에서 적어도 하나의 값이 두 번 이상 등장하면 `True` 반환 | ||
- 중복이 없으면: 배열의 모든 값이 유일하면 `False` 반환 | ||
""" | ||
|
||
""" | ||
First Try | ||
Time Complexity: | ||
- O(n) * O(n) = O(n^2): `for` 루프에서 `nums.count(i)`를 호출할 때마다 리스트를 순회하므로, 전체 시간 복잡도는 `O(n^2)` | ||
""" | ||
class Solution: | ||
def containsDuplicate(self, nums: List[int]) -> bool: | ||
for i in nums: | ||
if nums.count(i) > 1: | ||
return True | ||
return False | ||
|
||
""" | ||
Second Try (set를 활용하여 이미 본 요소를 효율적으로 추적하는 방법) | ||
Time Complexity: | ||
- O(n): `for` 루프에서 각 숫자에 대해 `in` 연산과 `add` 연산이 상수 시간 O(1)으로 처리되므로, 전체 시간 복잡도는 O(n) | ||
""" | ||
class Solution: | ||
def containsDuplicate(self, nums: List[int]) -> bool: | ||
seen = set() | ||
for i in nums: | ||
if i in seen: | ||
return True | ||
seen.add(i) | ||
return False |
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,28 @@ | ||
""" | ||
Title: 198. House Robber | ||
|
||
Constraints: | ||
- 1 <= nums.length <= 100 | ||
- 0 <= nums[i] <= 400 | ||
|
||
Time Complexity: | ||
- O(n) | ||
Space Complexity: | ||
- O(n) | ||
""" | ||
|
||
class Solution: | ||
def rob(self, nums: List[int]) -> int: | ||
|
||
if len(nums) == 1: | ||
return nums[0] | ||
elif len(nums) == 2: | ||
return max(nums[0], nums[1]) | ||
|
||
dp = [0]*len(nums) | ||
dp[0] = nums[0] | ||
dp[1] = max(nums[0], nums[1]) | ||
|
||
for i in range(2, len(nums)): | ||
dp[i] = max(dp[i-1], nums[i] + dp[i-2]) | ||
return dp[-1] |
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,38 @@ | ||
""" | ||
Title: 128. Longest Consecutive Sequence | ||
Link: https://leetcode.com/problems/longest-consecutive-sequence/ | ||
|
||
Question: | ||
- Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. | ||
- You must write an algorithm that runs in O(n) time. | ||
|
||
Constraints: | ||
- 0 <= nums.length <= 10^5 | ||
- -10^9 <= nums[i] <= 10^9 | ||
|
||
Time Complexity: | ||
- O(n log n) | ||
Space Complexity: | ||
- O(n) | ||
|
||
Notes: | ||
- sorted(nums)를 사용하면 TC가 O(n log n)이 되어 문제의 조건을 충족하지 못하지만, 이 방법이 제가 생각해서 풀 수 있는 최선이라 일단 이대로 제출합니다! 다른 분들 답안 참고하여 다시 풀어보겠습니다 :) | ||
""" | ||
|
||
class Solution: | ||
def longestConsecutive(self, nums: List[int]) -> int: | ||
nums = sorted(nums) | ||
max_length = 0 | ||
current_length = 1 | ||
|
||
for i in range(1, len(nums)): | ||
if nums[i] == nums[i-1] + 1: | ||
current_length += 1 | ||
elif nums[i] == nums[i-1]: | ||
continue | ||
else: | ||
max_length = max(max_length, current_length) | ||
current_length = 1 | ||
|
||
max_length = max(max_length, current_length) | ||
return max_length |
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,60 @@ | ||
""" | ||
Title: 237. Top K Frequent Elements | ||
Link: https://leetcode.com/problems/top-k-frequent-elements/ | ||
|
||
Question: | ||
- Given an integer array `nums` and an integer `k`, return the `k` most frequent elements. | ||
- You may return the answer in any order. | ||
|
||
Constraints: | ||
- 1 <= nums.length <= 10^5 | ||
- -10^4 <= nums[i] <= 10^4 | ||
- k is in the range [1, the number of unique elements in the array]. | ||
- The answer is guaranteed to be unique. | ||
|
||
Time Complexity: | ||
- O(n log n) | ||
Space Complexity: | ||
- O(n) | ||
""" | ||
|
||
# Original Solution | ||
class Solution: | ||
def topKFrequent(self, nums: List[int], k: int) -> List[int]: | ||
frequency = {} | ||
result = [] | ||
|
||
for num in nums: | ||
if num in frequency: | ||
frequency[num] += 1 | ||
else: | ||
frequency[num] = 1 | ||
|
||
sorted_frequency = sorted(frequency.items(), key=lambda x: x[1], reverse=True) | ||
|
||
for i in range(k): | ||
result.append(sorted_frequency[i][0]) | ||
|
||
return result | ||
|
||
# Improved Solution using Heap | ||
# Time Complexity: O(n log k) | ||
class Solution: | ||
def topKFrequent(self, nums: List[int], k: int) -> List[int]: | ||
frequency = {} | ||
result = [] | ||
heap = [] | ||
|
||
for num in nums: | ||
if num in frequency: | ||
frequency[num] += 1 | ||
else: | ||
frequency[num] = 1 | ||
|
||
for num, freq in frequency.items(): | ||
heapq.heappush(heap, (-freq, num)) | ||
|
||
for i in range(k): | ||
result.append(heapq.heappop(heap)[1]) | ||
|
||
return result |
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 @@ | ||
|
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,26 @@ | ||
""" | ||
Title: 215. Valid Palindrome | ||
Link: https://leetcode.com/problems/valid-palindrome/ | ||
|
||
Summary: | ||
- Palindrome이라면 True, 아니라면 False를 반환하는 문제. | ||
- Palindrome이란, 앞으로 읽어도 뒤에서부터 읽어도 동일한 단어를 뜻함. | ||
- 추가 조건: 대소문자를 구분하지 않으며, 알파벳과 숫자 이외의 문자는 제거해야 함. | ||
- e.g. racecar | ||
|
||
Conditions: | ||
- 입력 문자열이 Palindrome인 경우: `True` 반환 | ||
- Palindrome이 아닌 경우: `False` 반환 | ||
|
||
Time Complexity: | ||
- O(n) | ||
Space Complexity: | ||
- O(n) | ||
""" | ||
class Solution: | ||
def isPalindrome(self, s: str) -> bool: | ||
s = re.sub(r'[^a-zA-z0-9]', '', s).lower() | ||
if s == s[::-1]: | ||
return True | ||
return False | ||
|
Oops, something went wrong.
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.
잘 풀어주신 것 같습니다. 이후 문제에서 등장하는 시간복잡도 O(nlogk)를 만족하려면 어떤 방법이 필요할지 고민해보시면 좋을 것 같습니다! 전체 데이터가 다 필요한가에 대해서 고민해보면 해답을 떠올리실 수 있을 것 같습니다! (계속 정렬 상태를 유지하면 어떨까요?)
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.
리뷰 감사합니다! 말씀해주신 것 참고하여 다시 풀어보겠습니다 😁