Skip to content

Commit 6b57ed3

Browse files
committed
[WHYjun] WEEK 01 solutions - (3/5)
1 parent c10802e commit 6b57ed3

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed

contains-duplicate/WHYjun.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
class Solution:
2+
def containsDuplicate(self, nums: List[int]) -> bool:
3+
return len(set(nums)) != len(nums)

top-k-frequent-elements/WHYjun.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+
# Time complexity: O(nlogn)
4+
# Space Complexity: O(n)
5+
6+
if len(nums) <= k:
7+
return list(set(nums))
8+
9+
counts = {}
10+
for num in nums:
11+
if num not in counts:
12+
counts[num] = 0
13+
counts[num] += 1
14+
15+
# The key of dictionary is unique.
16+
sortedKeys = sorted(list(counts.keys()), key=lambda key: counts[key], reverse = True)
17+
return sortedKeys[:k]

two-sum/WHYjun.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+
memo = {}
4+
5+
for i, num in enumerate(nums):
6+
diff = target - num
7+
if diff in memo:
8+
# Each input would have exactly one solution
9+
return [memo[diff], i]
10+
memo[num] = i
11+
12+
return []

0 commit comments

Comments
 (0)