Skip to content

Commit 2975558

Browse files
authored
Merge pull request #2357 from sangbeenmoon/main
[sangbeenmoon] WEEK 1 Solutions
2 parents 9fc61ae + e731af4 commit 2975558

5 files changed

Lines changed: 85 additions & 0 deletions

File tree

contains-duplicate/sangbeenmoon.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# time : O(n)
2+
# space : O(n)
3+
class Solution:
4+
def containsDuplicate(self, nums: List[int]) -> bool:
5+
d = {}
6+
for num in nums:
7+
if num in d:
8+
return True
9+
else:
10+
d[num] = True
11+
return False

house-robber/sangbeenmoon.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# dp[i] = max(dp[i-2] + nums[i] , dp[i-1])
2+
# time : O(n)
3+
# space : O(n)
4+
class Solution:
5+
def rob(self, nums: List[int]) -> int:
6+
dp = [0] * len(nums)
7+
dp[0] = nums[0]
8+
9+
if len(nums) == 1:
10+
return dp[0]
11+
12+
dp[1] = max(dp[0], nums[1])
13+
for i in range(2, len(nums)):
14+
dp[i] = max(dp[i-2] + nums[i] , dp[i-1])
15+
16+
return dp[len(nums) - 1]
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# 30분 내로 풀지 못함. 풀이를 참고하였음.
2+
# idea : x - 1 이 존재하지 않는 x 값에서만 loop 를 실행한다.
3+
# time O(n) : 모든 숫자를 많아야 1,2번 방문.
4+
# space O(n)
5+
class Solution:
6+
def longestConsecutive(self, nums: List[int]) -> int:
7+
s = set(nums)
8+
answer = 0
9+
for num in s:
10+
if num - 1 not in s:
11+
cur = num - 1
12+
length = 0
13+
while cur + 1 in s:
14+
cur = cur + 1
15+
length = length + 1
16+
answer = max(answer , length)
17+
18+
return answer
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# idea
2+
# 1. 빈도수를 dict 에 저장한다.
3+
# 2. 빈도수 내림차순으로 정렬한다.
4+
# 3. 2에서 정렬한 entry 중 1번째, 2번째, ... k 번째 key 값을 모아서 List 로 반환한다.
5+
# time : O(nlogn)
6+
# space : O(n)
7+
class Solution:
8+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
9+
count_dict = {}
10+
11+
for num in nums:
12+
if num in count_dict:
13+
count_dict[num] = count_dict[num] + 1
14+
else:
15+
count_dict[num] = 1
16+
17+
tuple_list = []
18+
19+
for (count_key, count_value) in count_dict.items():
20+
tuple_list.append((count_key, count_value))
21+
22+
sorted_tuple_list = sorted(tuple_list, key=lambda x: x[1], reverse=True)
23+
answer = []
24+
25+
for i in range(k):
26+
answer.append(sorted_tuple_list[i][0])
27+
28+
return answer
29+
30+
31+

two-sum/sangbeenmoon.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# time : O(n^2)
2+
# space : O(1)
3+
class Solution:
4+
def twoSum(self, nums: List[int], target: int) -> List[int]:
5+
for i in range(len(nums)):
6+
for j in range(i + 1, len(nums)):
7+
if nums[i] + nums[j] == target:
8+
return [i,j]
9+

0 commit comments

Comments
 (0)