Skip to content

Commit 3fd1331

Browse files
authored
[freemjstudio] WEEK 1 Solutions (#2674)
* freemjstudio/two-sum * freemjstudio: contains-duplicate (easy, python) * freemjstudio: contains-duplicate * freemjstudio: top k frequent elements * liner ์ ์šฉ
1 parent 72c25c7 commit 3fd1331

3 files changed

Lines changed: 49 additions & 0 deletions

File tree

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
class Solution:
2+
def containsDuplicate(self, nums: List[int]) -> bool:
3+
first = len(nums) # O(1) : ๋ฆฌ์ŠคํŠธ ๊ฐ์ฒด๋Š” ์ด๋ฏธ ์ž๊ธฐ์ž์‹ ์˜ ๊ธธ์ด๋ฅผ ์ €์žฅํ•˜๊ณ  ์žˆ์Œ
4+
set_nums = set(nums) # O(N)
5+
second = len(set_nums)
6+
return (first != second)
7+
8+
# ์‹œ๊ฐ„ ๋ณต์žก๋„ : O(N)
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import heapq
2+
3+
class Solution:
4+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
5+
answer = []
6+
count = dict()
7+
heap = []
8+
if len(nums) <= 1:
9+
return nums
10+
# O(N)
11+
for num in nums:
12+
count[num] = count.get(num, 0) + 1
13+
14+
# heap ์˜ ํฌ๊ธฐ๋Š” ์ตœ๋Œ€ k ๋กœ ์ œํ•œํ•จ.
15+
# unique ํ•œ M๊ฐœ์˜ ์ˆซ์ž๋ฅผ ์„ ํ˜• ์ˆœํšŒ O(M)
16+
for num, freq in count.items():
17+
if len(heap) < k:
18+
heapq.heappush(heap, (freq, num)) # O(logK)
19+
else:
20+
if heap[0][0] < freq:
21+
heapq.heappop(heap) # O(logK)
22+
heapq.heappush(heap, (freq, num)) # O(logK)
23+
24+
for _ in range(k):
25+
k, v = heapq.heappop(heap)
26+
answer.append(v)
27+
28+
return answer
29+

โ€Žtwo-sum/freemjstudio.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+
answer = []
4+
hashmap = dict()
5+
for i in range(len(nums)):
6+
current_num = nums[i]
7+
diff = target - current_num
8+
if diff in hashmap.keys():
9+
return [i, hashmap[diff]]
10+
hashmap[current_num] = i # store the index of current num
11+
12+
return answer

0 commit comments

Comments
ย (0)