Skip to content

Commit 71df1cf

Browse files
committed
add rivkode 1-3 questions
1 parent 53ce7c7 commit 71df1cf

File tree

3 files changed

+51
-13
lines changed

3 files changed

+51
-13
lines changed

contains-duplicate/rivkode.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,14 @@
55
# The size of the set for storing deduplicated elements is proportional to the length of the input list.
66

77
class Solution:
8-
def containsDuplicate(self, nums: list[int]) -> bool:
9-
list_len = len(nums)
10-
set_len = len(set(nums))
8+
def containsDuplicate(self, nums):
9+
list_num = len(nums)
10+
set_num = len(set(nums))
1111

12-
return list_len != set_len
12+
if list_num != set_num:
13+
return True
14+
else:
15+
return False
1316

1417
if __name__ == "__main__":
1518
solution = Solution()

top-k-frequent-elements/rivkode.py

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,18 +8,35 @@
88
# - and when sorting takes O(n), hash[x] occupy O(1)
99

1010
class Solution:
11-
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
12-
hash = dict()
11+
def topKFrequent(self, nums, k):
12+
"""
13+
:type nums: List[int]
14+
:type k: int
15+
:rtype: List[int]
16+
"""
1317

14-
# for loop nums to set count for each element in hash(dictionary)
15-
for num in nums:
16-
if num in hash:
17-
hash[num] += 1
18+
dic = {}
19+
20+
for v in nums:
21+
if v in dic:
22+
cur = dic[v]
23+
cur += 1
24+
dic[v] = cur
1825
else:
19-
hash[num] = 1
26+
dic[v] = 1
27+
28+
reverse_desc = sorted(dic.items(), key=lambda item: item[1], reverse=True)
2029

21-
# sort (TimSort), using lambda function to set a sorting key which is a count
22-
return sorted(hash, key=lambda x: hash[x], reverse=True)[:k]
30+
n = 0
31+
result = []
32+
for v in reverse_desc:
33+
if n == k:
34+
break
35+
36+
result.append(v[0])
37+
n += 1
38+
39+
return result
2340

2441
if __name__ == "__main__":
2542
solution = Solution()

two-sum/rivkode.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution(object):
2+
def twoSum(self, nums, target):
3+
4+
"""
5+
:type nums: List[int]
6+
:type target: int
7+
:rtype: List[int]
8+
"""
9+
10+
dic = {}
11+
12+
for i, v in enumerate(nums):
13+
complement = target - v
14+
15+
if complement in dic:
16+
return [i, dic[complement]]
17+
18+
dic[v] = i

0 commit comments

Comments
 (0)