Skip to content

Commit d0f8e0c

Browse files
author
MJ Kang
committed
Merge branch 'week1'
2 parents 4048621 + b9cd6b6 commit d0f8e0c

File tree

3 files changed

+63
-0
lines changed

3 files changed

+63
-0
lines changed

house-robber/mandoolala.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
from typing import List
2+
3+
class Solution:
4+
def rob(self, nums: List[int]) -> int:
5+
'''
6+
[Complexity]
7+
Time: O(n)
8+
Space: O(n)
9+
'''
10+
cnt = len(nums)
11+
12+
if cnt == 1:
13+
return nums[0]
14+
if cnt == 2:
15+
return max(nums[0], nums[1])
16+
17+
dp = [0] * cnt
18+
dp[0] = nums[0]
19+
dp[1] = max(nums[0], nums[1])
20+
21+
for i in range(2, cnt):
22+
# skip: dp[i-1]
23+
# rob: dp[i-2]+nums[i]
24+
dp[i] = max(dp[i - 1], dp[i - 2] + nums[i])
25+
return max(dp)
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
from typing import List
2+
3+
class Solution:
4+
def longestConsecutive(self, nums: List[int]) -> int:
5+
num_set = set(nums)
6+
longest = 0
7+
for num in num_set:
8+
if num - 1 in num_set:
9+
continue
10+
length = 1
11+
while num + length in num_set:
12+
length += 1
13+
longest = max(length, longest)
14+
return longest

top-k-frequent-elements/mandoolala.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,29 @@
33

44
class Solution:
55
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
6+
'''
7+
Using (min)heap
8+
[Complexity]
9+
Time: O(log n)
10+
Space: O(n+k)
11+
'''
12+
from heapq import heappush, heappop
13+
counter = {}
14+
for num in nums:
15+
counter[num] = counter.get(num, 0) + 1
16+
heap = []
17+
for num, freq in counter.items():
18+
heappush(heap, (freq, num))
19+
if len(heap) > k:
20+
heappop(heap)
21+
return [num for _, num in heap]
22+
'''
23+
Using hash table
24+
[Complexity]
25+
Time: O(n log n)
26+
Space: O(n)
27+
'''
28+
'''
629
countDict = {}
730
for num in nums:
831
if num in countDict:
@@ -14,3 +37,4 @@ def topKFrequent(self, nums: List[int], k: int) -> List[int]:
1437
for i in range(k):
1538
freqElements.append(sortedDictList[i][0])
1639
return freqElements
40+
'''

0 commit comments

Comments
 (0)