Skip to content

Commit 469675e

Browse files
committed
[Leo] 5th Week solutions
1 parent 9ee7b25 commit 469675e

File tree

2 files changed

+43
-0
lines changed
  • encode-and-decode-strings
  • top-k-frequent-elements

2 files changed

+43
-0
lines changed

encode-and-decode-strings/Leo.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Codec:
2+
def encode(self, strs: List[str]) -> str:
3+
"""Encodes a list of strings to a single string.
4+
"""
5+
res = ''
6+
7+
for s in strs:
8+
res += str(len(s)) + '#' + s
9+
10+
return res
11+
12+
def decode(self, s: str) -> List[str]:
13+
"""Decodes a single string to a list of strings.
14+
"""
15+
res = []
16+
17+
i = 0
18+
while i < len(s):
19+
a = s.find('#', i)
20+
length = int(s[i:a])
21+
res.append(s[a + 1:a + 1 + length])
22+
i = a + 1 + length
23+
24+
return res
25+
26+
## TC: O(n), SC:O(n),n denotes sum of all len(s)

top-k-frequent-elements/Leo.py

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+
4+
num_dict = collections.Counter(nums)
5+
freq = num_dict.most_common()
6+
ans = []
7+
8+
for key, val in freq:
9+
if k == 0:
10+
break
11+
12+
ans.append(key)
13+
k -= 1
14+
15+
return ans
16+
17+
## TC: O(n * logn), SC: O(n)

0 commit comments

Comments
 (0)