Skip to content

Commit cecb0bf

Browse files
authored
Merge pull request #1683 from hi-rachel/main
[hi-rachel] WEEK 01 solutions
2 parents 6bb898f + 8972f8d commit cecb0bf

File tree

5 files changed

+134
-27
lines changed

5 files changed

+134
-27
lines changed

contains-duplicate/hi-rachel.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""
2+
https://leetcode.com/problems/contains-duplicate/
3+
4+
Given an integer array nums,
5+
return true if any value appears at least twice in the array,
6+
and return false if every element is distinct.
7+
8+
TC: O(n)
9+
SC: O(n)
10+
"""
11+
12+
from typing import List
13+
14+
class Solution:
15+
def containsDuplicate(self, nums: List[int]) -> bool:
16+
seen = set()
17+
18+
for num in nums:
19+
if num in seen:
20+
return True
21+
else:
22+
seen.add(num)
23+
return False
24+
25+
26+
class Solution:
27+
def containsDuplicate(self, nums: List[int]) -> bool:
28+
return len(set(nums)) != len(nums)

house-robber/hi-rachel.py

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,20 +10,38 @@
1010
# **dp[i] = max(dp[i-1], dp[i-2] + nums[i])**
1111
# nums 길이가 2인 경우 range(2, 2)는 for문 안 돈다.
1212

13+
from typing import List
14+
1315
class Solution:
1416
def rob(self, nums: List[int]) -> int:
15-
if not nums: return 0
16-
if len(nums) == 1: return nums[0]
17-
17+
if len(nums) == 1:
18+
return nums[0]
19+
1820
dp = [0] * len(nums)
1921
dp[0] = nums[0]
2022
dp[1] = max(nums[0], nums[1])
2123

2224
for i in range(2, len(nums)):
23-
dp[i] = max(dp[i - 1], nums[i] + dp[i - 2])
25+
dp[i] = max(dp[i - 1], dp[i - 2] + nums[i])
2426

2527
return dp[-1]
2628

29+
"""
30+
공간 최적화 풀이
31+
32+
prev2: i-2까지의 최대값 + 현재 돈
33+
prev1: i번째 집 안 털고, 이전까지의 최대값 유지
34+
35+
TC: O(n)
36+
SC: O(1)
37+
"""
38+
class Solution:
39+
def rob(self, nums: List[int]) -> int:
40+
prev2, prev1 = 0, 0
41+
for num in nums:
42+
prev2, prev1 = prev1, max(prev1, prev2 + num)
43+
return prev1
44+
2745

2846
# TS 코드
2947
# function rob(nums: number[]): number {

longest-consecutive-sequence/hi-rachel.py

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
# 처음 풀이
22
# O(n log n) time, O(n) space
33

4+
from typing import List
5+
46
class Solution:
57
def longestConsecutive(self, nums: List[int]) -> int:
68
if nums == []:
@@ -67,11 +69,19 @@ def longestConsecutive(self, nums: List[int]) -> int:
6769
return longest
6870

6971

70-
# 최종 개선 풀이
71-
# O(n) time, O(n) space
72-
# 위 풀이에서 한쪽으로 구간을 찾지 않고, 양쪽으로 찾으며 숫자를 집합에서 제거하며
73-
# 집합에서 원소가 하나도 남지 않을 때까지 하면 가장 긴 구간의 길이를 구할 수 있다.
74-
# 배열의 모든 정수를 set에 저장했으므로 공간 복잡도는 O(n)
72+
"""
73+
최종 개선 풀이
74+
O(n) time, O(n) space
75+
76+
위 풀이에서 한쪽으로 구간을 찾지 않고, 양쪽으로 찾으며 숫자를 집합에서 제거하며
77+
집합에서 원소가 하나도 남지 않을 때까지 하면 가장 긴 구간의 길이를 구할 수 있다.
78+
79+
배열의 모든 정수를 set에 저장했으므로 공간 복잡도는 O(n), 시간 복잡도 O(n)
80+
set 삽입: O(1), 삭제: 평균 O(1), 순서 보장 x => 순서를 무시하고 존재 여부(빠른 탐색)이 중요할 때 사용.
81+
존재하지 않는 값을 pop(), remove()시 KeyError 주의
82+
83+
max(a, b): 두 값 중 큰 값을 반환 → O(1)
84+
"""
7585

7686
class Solution:
7787
def longestConsecutive(self, nums: List[int]) -> int:
@@ -93,6 +103,28 @@ def longestConsecutive(self, nums: List[int]) -> int:
93103

94104
return longest
95105

106+
"""
107+
25/7/23 복습, 위 최적화 풀이로 풀지 못함
108+
TC: O(n log n)
109+
SC: O(n)
110+
"""
111+
class Solution:
112+
def longestConsecutive(self, nums: List[int]) -> int:
113+
if not nums:
114+
return 0
115+
nums = sorted(list(set(nums)))
116+
max_cnt = 1
117+
cnt = 1
118+
119+
for i in range(len(nums) - 1):
120+
if nums[i] + 1 == nums[i + 1]:
121+
cnt += 1
122+
max_cnt = max(max_cnt, cnt)
123+
else:
124+
cnt = 1
125+
126+
return max_cnt
127+
96128
# TS 풀이
97129
# O(n) time, O(n) space
98130
# JavaScript Set에서 값을 꺼내고자 할때는 **numSet.values().next().value** 사용

top-k-frequent-elements/hi-rachel.py

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,19 @@
1-
# 가장 자주 등장한 상위 K개의 문자 배열 반환
2-
# O(n log n) time, O(n) space
1+
"""
2+
https://leetcode.com/problems/top-k-frequent-elements/
3+
4+
Given an integer array nums and an integer k, return the k most frequent elements.
5+
You may return the answer in any order.
6+
7+
TC: O(n log n)
8+
SC: O(n)
9+
"""
310

411
from collections import defaultdict
12+
from typing import List
513

614
class Solution:
715
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
8-
numdict = defaultdict(int);
16+
numdict = defaultdict(int)
917

1018
for num in nums:
1119
numdict[num] += 1
@@ -15,3 +23,14 @@ def topKFrequent(self, nums: List[int], k: int) -> List[int]:
1523
keys = list(sort_dict)
1624

1725
return keys[:k]
26+
27+
# heapq 풀이
28+
from collections import Counter
29+
import heapq
30+
31+
class Solution:
32+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
33+
counter = Counter(nums)
34+
return heapq.nlargest(k, counter.keys(), key=counter.get)
35+
36+

two-sum/hi-rachel.py

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,17 @@
11
"""
2-
처음 풀이
3-
O(N^2) time, O(N) space
4-
"""
2+
https://leetcode.com/problems/two-sum/
53
6-
# class Solution:
7-
# def twoSum(self, nums: List[int], target: int) -> List[int]:
8-
# result = []
9-
# for i in range(len(nums)):
10-
# rest = target - nums[i]
11-
# rest_nums = nums[i+1:]
12-
# if rest in rest_nums:
13-
# result.extend([i, rest_nums.index(rest)+i+1])
14-
# break
15-
# return result
16-
4+
Given an array of integers nums and an integer target,
5+
return indices of the two numbers such that they add up to target.
6+
You may assume that each input would have exactly one solution, and you may not use the same element twice.
7+
You can return the answer in any order.
178
18-
"""
199
개선 코드
2010
O(N) time, O(N) space
2111
"""
2212

13+
from typing import List
14+
2315
class Solution:
2416
def twoSum(self, nums: List[int], target: int) -> List[int]:
2517
indices = {}
@@ -31,6 +23,24 @@ def twoSum(self, nums: List[int], target: int) -> List[int]:
3123
return [i, j]
3224
indices[v] = i
3325

26+
27+
"""
28+
처음 풀이
29+
O(N^2) time, O(N) space
30+
"""
31+
32+
# class Solution:
33+
# def twoSum(self, nums: List[int], target: int) -> List[int]:
34+
# result = []
35+
# for i in range(len(nums)):
36+
# rest = target - nums[i]
37+
# rest_nums = nums[i+1:]
38+
# if rest in rest_nums:
39+
# result.extend([i, rest_nums.index(rest)+i+1])
40+
# break
41+
# return result
42+
43+
3444
# JS 풀이
3545
# /**
3646
# * @param {number[]} nums

0 commit comments

Comments
 (0)