Skip to content

Commit 6ccc41c

Browse files
authored
Merge pull request #656 from KwonNayeon/main
[KwonNayeon] Week 1
2 parents d0d1fb8 + 2173819 commit 6ccc41c

File tree

6 files changed

+192
-0
lines changed

6 files changed

+192
-0
lines changed

contains-duplicate/KwonNayeon.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""
2+
Title: 217. Contains Duplicate
3+
Link: https://leetcode.com/problems/contains-duplicate/
4+
5+
Summary:
6+
- 주어진 배열 `nums`에서 어떤 값이 한 번 이상 등장하면 True를 반환하고, 배열의 모든 값이 유일한 경우에는 False를 반환함
7+
- Input: `nums = [1,2,3,1]`
8+
- Output: `True`
9+
10+
Conditions:
11+
- 중복이 있으면: 배열에서 적어도 하나의 값이 두 번 이상 등장하면 `True` 반환
12+
- 중복이 없으면: 배열의 모든 값이 유일하면 `False` 반환
13+
"""
14+
15+
"""
16+
First Try
17+
Time Complexity:
18+
- O(n) * O(n) = O(n^2): `for` 루프에서 `nums.count(i)`를 호출할 때마다 리스트를 순회하므로, 전체 시간 복잡도는 `O(n^2)`
19+
"""
20+
class Solution:
21+
def containsDuplicate(self, nums: List[int]) -> bool:
22+
for i in nums:
23+
if nums.count(i) > 1:
24+
return True
25+
return False
26+
27+
"""
28+
Second Try (set를 활용하여 이미 본 요소를 효율적으로 추적하는 방법)
29+
Time Complexity:
30+
- O(n): `for` 루프에서 각 숫자에 대해 `in` 연산과 `add` 연산이 상수 시간 O(1)으로 처리되므로, 전체 시간 복잡도는 O(n)
31+
"""
32+
class Solution:
33+
def containsDuplicate(self, nums: List[int]) -> bool:
34+
seen = set()
35+
for i in nums:
36+
if i in seen:
37+
return True
38+
seen.add(i)
39+
return False

house-robber/KwonNayeon.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""
2+
Title: 198. House Robber
3+
4+
Constraints:
5+
- 1 <= nums.length <= 100
6+
- 0 <= nums[i] <= 400
7+
8+
Time Complexity:
9+
- O(n)
10+
Space Complexity:
11+
- O(n)
12+
"""
13+
14+
class Solution:
15+
def rob(self, nums: List[int]) -> int:
16+
17+
if len(nums) == 1:
18+
return nums[0]
19+
elif len(nums) == 2:
20+
return max(nums[0], nums[1])
21+
22+
dp = [0]*len(nums)
23+
dp[0] = nums[0]
24+
dp[1] = max(nums[0], nums[1])
25+
26+
for i in range(2, len(nums)):
27+
dp[i] = max(dp[i-1], nums[i] + dp[i-2])
28+
return dp[-1]
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
"""
2+
Title: 128. Longest Consecutive Sequence
3+
Link: https://leetcode.com/problems/longest-consecutive-sequence/
4+
5+
Question:
6+
- Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
7+
- You must write an algorithm that runs in O(n) time.
8+
9+
Constraints:
10+
- 0 <= nums.length <= 10^5
11+
- -10^9 <= nums[i] <= 10^9
12+
13+
Time Complexity:
14+
- O(n log n)
15+
Space Complexity:
16+
- O(n)
17+
18+
Notes:
19+
- sorted(nums)를 사용하면 TC가 O(n log n)이 되어 문제의 조건을 충족하지 못하지만, 이 방법이 제가 생각해서 풀 수 있는 최선이라 일단 이대로 제출합니다! 다른 분들 답안 참고하여 다시 풀어보겠습니다 :)
20+
"""
21+
22+
class Solution:
23+
def longestConsecutive(self, nums: List[int]) -> int:
24+
nums = sorted(nums)
25+
max_length = 0
26+
current_length = 1
27+
28+
for i in range(1, len(nums)):
29+
if nums[i] == nums[i-1] + 1:
30+
current_length += 1
31+
elif nums[i] == nums[i-1]:
32+
continue
33+
else:
34+
max_length = max(max_length, current_length)
35+
current_length = 1
36+
37+
max_length = max(max_length, current_length)
38+
return max_length

top-k-frequent-elements/KwonNayeon.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
"""
2+
Title: 237. Top K Frequent Elements
3+
Link: https://leetcode.com/problems/top-k-frequent-elements/
4+
5+
Question:
6+
- Given an integer array `nums` and an integer `k`, return the `k` most frequent elements.
7+
- You may return the answer in any order.
8+
9+
Constraints:
10+
- 1 <= nums.length <= 10^5
11+
- -10^4 <= nums[i] <= 10^4
12+
- k is in the range [1, the number of unique elements in the array].
13+
- The answer is guaranteed to be unique.
14+
15+
Time Complexity:
16+
- O(n log n)
17+
Space Complexity:
18+
- O(n)
19+
"""
20+
21+
# Original Solution
22+
class Solution:
23+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
24+
frequency = {}
25+
result = []
26+
27+
for num in nums:
28+
if num in frequency:
29+
frequency[num] += 1
30+
else:
31+
frequency[num] = 1
32+
33+
sorted_frequency = sorted(frequency.items(), key=lambda x: x[1], reverse=True)
34+
35+
for i in range(k):
36+
result.append(sorted_frequency[i][0])
37+
38+
return result
39+
40+
# Improved Solution using Heap
41+
# Time Complexity: O(n log k)
42+
class Solution:
43+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
44+
frequency = {}
45+
result = []
46+
heap = []
47+
48+
for num in nums:
49+
if num in frequency:
50+
frequency[num] += 1
51+
else:
52+
frequency[num] = 1
53+
54+
for num, freq in frequency.items():
55+
heapq.heappush(heap, (-freq, num))
56+
57+
for i in range(k):
58+
result.append(heapq.heappop(heap)[1])
59+
60+
return result

valid-anagram/KwonNayeon.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+

valid-palindrome/KwonNayeon.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
"""
2+
Title: 215. Valid Palindrome
3+
Link: https://leetcode.com/problems/valid-palindrome/
4+
5+
Summary:
6+
- Palindrome이라면 True, 아니라면 False를 반환하는 문제.
7+
- Palindrome이란, 앞으로 읽어도 뒤에서부터 읽어도 동일한 단어를 뜻함.
8+
- 추가 조건: 대소문자를 구분하지 않으며, 알파벳과 숫자 이외의 문자는 제거해야 함.
9+
- e.g. racecar
10+
11+
Conditions:
12+
- 입력 문자열이 Palindrome인 경우: `True` 반환
13+
- Palindrome이 아닌 경우: `False` 반환
14+
15+
Time Complexity:
16+
- O(n)
17+
Space Complexity:
18+
- O(n)
19+
"""
20+
class Solution:
21+
def isPalindrome(self, s: str) -> bool:
22+
s = re.sub(r'[^a-zA-z0-9]', '', s).lower()
23+
if s == s[::-1]:
24+
return True
25+
return False
26+

0 commit comments

Comments
 (0)