Skip to content

[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 14 commits into from
Dec 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions contains-duplicate/KwonNayeon.py
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
28 changes: 28 additions & 0 deletions house-robber/KwonNayeon.py
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]
38 changes: 38 additions & 0 deletions longest-consecutive-sequence/KwonNayeon.py
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
60 changes: 60 additions & 0 deletions top-k-frequent-elements/KwonNayeon.py
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)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

잘 풀어주신 것 같습니다. 이후 문제에서 등장하는 시간복잡도 O(nlogk)를 만족하려면 어떤 방법이 필요할지 고민해보시면 좋을 것 같습니다! 전체 데이터가 다 필요한가에 대해서 고민해보면 해답을 떠올리실 수 있을 것 같습니다! (계속 정렬 상태를 유지하면 어떨까요?)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

리뷰 감사합니다! 말씀해주신 것 참고하여 다시 풀어보겠습니다 😁


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
1 change: 1 addition & 0 deletions valid-anagram/KwonNayeon.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

26 changes: 26 additions & 0 deletions valid-palindrome/KwonNayeon.py
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

Loading