Skip to content

Commit 3b35523

Browse files
authored
Merge pull request #1994 from changhyumm/main
[changhyumm] WEEK 01 solutions
2 parents 5c15cc6 + f0a962d commit 3b35523

File tree

5 files changed

+70
-0
lines changed

5 files changed

+70
-0
lines changed

contains-duplicate/changhyumm.py

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

house-robber/changhyumm.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution:
2+
def rob(self, nums: List[int]) -> int:
3+
n = len(nums)
4+
# 집이 하나면 최대 profit은 그 자체
5+
if n == 1:
6+
return nums[0]
7+
8+
# dp[i]를 i+1 집까지 털었을때의 max라고 정의
9+
# dp[i] = max(dp[i-1], nums[i] + dp[i-2])
10+
dp = [0] * n
11+
dp[0] = nums[0]
12+
dp[1] = max(nums[0], nums[1])
13+
14+
# dp를 누적
15+
for i in range(2, n):
16+
dp[i] = max(dp[i-1], nums[i] + dp[i-2])
17+
18+
# time O(n) - loop 1번
19+
# space O(n) - dp 배열
20+
return dp[-1]
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
class Solution:
2+
def longestConsecutive(self, nums: List[int]) -> int:
3+
num_set = set(nums)
4+
max_length = 0
5+
6+
for num in num_set:
7+
if num - 1 not in num_set:
8+
length = 1
9+
while num + length in num_set:
10+
length += 1
11+
max_length = max(max_length, length)
12+
return max_length
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution:
2+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
3+
freq = dict()
4+
for num in nums:
5+
if num in freq:
6+
freq[num] += 1
7+
else:
8+
freq[num] = 1
9+
10+
result = sorted(freq.items(), key=lambda x: x[1], reverse=True)
11+
ans = []
12+
idx = 0
13+
while k > 0:
14+
ans.append(result[idx][0])
15+
idx += 1
16+
k -= 1
17+
return ans

two-sum/changhyumm.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
class Solution:
2+
def twoSum(self, nums: List[int], target: int) -> List[int]:
3+
# for i in range(len(nums)):
4+
# for j in range(i+1, len(nums)):
5+
# if nums[i] + nums[j] == target:
6+
# return [i, j]
7+
dic = dict()
8+
for idx, num in enumerate(nums):
9+
if target - num in dic:
10+
return [idx, dic[target-num]]
11+
else:
12+
dic[num] = idx

0 commit comments

Comments
 (0)