Skip to content

Commit 57b8fab

Browse files
author
mykoo
committed
Merge remote-tracking branch 'upstream/main'
2 parents 3cd7442 + 62207e0 commit 57b8fab

29 files changed

+1169
-0
lines changed

3sum/HC-kang.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* https://leetcode.com/problems/3sum/description
3+
* T.C: O(n^2)
4+
* S.C: O(1)
5+
*/
6+
function threeSum(nums: number[]): number[][] {
7+
nums.sort((a, b) => a - b);
8+
9+
const result: number[][] = [];
10+
11+
for (let i = 0; i < nums.length - 2; i++) { // O(n)
12+
if (i > 0 && nums[i] == nums[i - 1]) continue;
13+
14+
let left = i + 1;
15+
let right = nums.length - 1;
16+
17+
while (left < right) { // O(n)
18+
const sum = nums[i] + nums[left] + nums[right];
19+
if (sum == 0) {
20+
result.push([nums[i], nums[left], nums[right]]);
21+
22+
while (left < right && nums[left] == nums[left + 1]) left++;
23+
while (left < right && nums[right] == nums[right - 1]) right--;
24+
25+
left++;
26+
right--;
27+
} else if (sum < 0) {
28+
left++;
29+
} else {
30+
right--;
31+
}
32+
}
33+
}
34+
35+
return result;
36+
}

3sum/flynn.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
'''
2+
풀이
3+
- 중복되는 triplet을 피하기 위해 배열 nums를 정렬합니다
4+
- nums를 순회하며 이중 반복문을 수행하여 res 배열을 만듭니다
5+
- 중복되는 triplet을 피하기 위해 appended set을 이용합니다
6+
7+
Big O
8+
- N: 배열 nums의 크기
9+
10+
- Time complexity: O(N^2)
11+
- nums를 정렬하는데 걸리는 시간은 NlogN 형태로 증가합니다
12+
- 이중 반복문을 실행하는데 걸리는 시간은 N^2 형태로 증가합니다
13+
- O(NlogN + N^2)에서 증가율이 가장 큰 항은 N^2이므로 시간복잡도는 O(N^2)이라고 볼 수 있습니다
14+
15+
- Space complexity: O(N)
16+
- nums를 정렬한 배열을 복사하여 sorted_nums에 저장하였고 이에 필요한 공간은 N의 형태로 증가합니다
17+
- 첫번째 반복문 안의 store은 최대 N만큼 커질 수 있습니다
18+
- appended 집합은 nums의 모든 원소가 고유하더라도 N보다 커질 수 없습니다
19+
'''
20+
21+
class Solution:
22+
def threeSum(self, nums: List[int]) -> List[List[int]]:
23+
n = len(nums)
24+
25+
sorted_nums = sorted(nums)
26+
27+
res = []
28+
29+
for i in range(n - 2):
30+
first = sorted_nums[i]
31+
32+
if i > 0 and first == sorted_nums[i - 1]:
33+
continue
34+
35+
store = {}
36+
store[-first - sorted_nums[i + 1]] = sorted_nums[i + 1]
37+
38+
appended = set()
39+
40+
for j in range(i + 2, n):
41+
second = sorted_nums[j]
42+
43+
if second in store and second not in appended:
44+
res.append([first, store[second], second])
45+
appended.add(second)
46+
store[-first - second] = second
47+
48+
return res

3sum/hwanmini.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// 시간복잡도 O(n2)
2+
// 공간복잡도 O(k) (k는 결과 개수)
3+
/**
4+
* @param {number[]} nums
5+
* @return {number[][]}
6+
*/
7+
var threeSum = function(nums) {
8+
nums.sort((a, b) => a - b);
9+
10+
let result = []
11+
12+
for (let i = 0 ; i <= nums.length - 2; i++) {
13+
if (i > 0 && nums[i] === nums[i-1]) continue
14+
15+
const curNum = nums[i]
16+
let leftIdx = i+1;
17+
let rightIdx = nums.length - 1;
18+
19+
while (leftIdx < rightIdx) {
20+
const leftNum = nums[leftIdx]
21+
const rightNum = nums[rightIdx]
22+
const threeSum = curNum + leftNum + rightNum
23+
if (threeSum === 0) {
24+
result.push([curNum, leftNum, rightNum])
25+
while (leftIdx < rightIdx && nums[leftIdx] === nums[leftIdx+1]) leftIdx++
26+
while (leftIdx < rightIdx && nums[rightIdx] === nums[rightIdx-1]) rightIdx--
27+
leftIdx++
28+
rightIdx--
29+
} else if (threeSum < 0) {
30+
leftIdx = leftIdx + 1
31+
} else if (threeSum > 0) {
32+
rightIdx = rightIdx - 1
33+
}
34+
}
35+
36+
}
37+
38+
return result
39+
};

3sum/kayden.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
class Solution:
2+
3+
# 해시맵
4+
# 시간복잡도: O(N^2)
5+
# 공간복잡도: O(N)
6+
def threeSum(self, nums: List[int]) -> List[List[int]]:
7+
n = len(nums)
8+
nums.sort()
9+
10+
check = {}
11+
for idx, num in enumerate(nums):
12+
check[num] = idx
13+
14+
answer = set()
15+
for i in range(n-2):
16+
if nums[i] > 0:
17+
break
18+
if i > 0 and nums[i] == nums[i-1]:
19+
continue
20+
for j in range(i + 1, n):
21+
target = -(nums[i] + nums[j])
22+
if not check.get(target):
23+
continue
24+
if j >= check[target]:
25+
continue
26+
27+
answer.add((nums[i], nums[j], target))
28+
29+
return list(answer)
30+
31+
# 투포인터
32+
# 시간복잡도: O(N^2)
33+
# 공간복잡도: O(N)
34+
def threeSum2(self, nums: List[int]) -> List[List[int]]:
35+
n = len(nums)
36+
nums.sort()
37+
38+
answer = set()
39+
for i in range(n-2):
40+
if nums[i] > 0:
41+
break
42+
if i > 0 and nums[i] == nums[i-1]:
43+
continue
44+
l, r = i+1, n-1
45+
while l<r:
46+
if nums[l] + nums[r] == -nums[i]:
47+
answer.add((nums[i], nums[l], nums[r]))
48+
l += 1
49+
r -= 1
50+
while nums[l] == nums[l - 1] and l < r:
51+
l += 1
52+
53+
while nums[r] == nums[r + 1] and l < r:
54+
r -= 1
55+
56+
if nums[l] + nums[r] < -nums[i]:
57+
l += 1
58+
59+
if nums[l] + nums[r] > -nums[i]:
60+
r -= 1
61+
62+
return list(answer)

3sum/taekwon-dev.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* 시간 복잡도: O(n^2)
3+
* 공간 복잡도: O(n)
4+
*/
5+
class Solution {
6+
public List<List<Integer>> threeSum(int[] nums) {
7+
int left, right, sum;
8+
List<List<Integer>> results = new ArrayList<>();
9+
Arrays.sort(nums);
10+
11+
for (int i = 0; i < nums.length - 2; i++) {
12+
if (i > 0 && nums[i] == nums[i - 1]) {
13+
continue;
14+
}
15+
16+
left = i + 1;
17+
right = nums.length - 1;
18+
19+
while (left < right) {
20+
sum = nums[i] + nums[left] + nums[right];
21+
22+
if (sum < 0) {
23+
left++;
24+
} else if (sum > 0) {
25+
right--;
26+
} else {
27+
results.add(Arrays.asList(nums[i], nums[left], nums[right]));
28+
29+
while (left < right && nums[left] == nums[left + 1]) {
30+
left++;
31+
}
32+
while (left < right && nums[right] == nums[right - 1]) {
33+
right--;
34+
}
35+
left++;
36+
right--;
37+
}
38+
}
39+
}
40+
return results;
41+
}
42+
}

3sum/tolluset.ts

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/*
2+
* TC: O(n^2)
3+
* SC: O(n)
4+
* */
5+
function threeSum(nums: number[]): number[][] {
6+
const n = nums.length;
7+
const res: number[][] = [];
8+
9+
nums.sort((a, b) => a - b);
10+
11+
for (let i = 0; i < n - 2; i++) {
12+
if (i > 0 && nums[i] === nums[i - 1]) {
13+
continue;
14+
}
15+
16+
let left = i + 1,
17+
right = n - 1;
18+
19+
while (left < right) {
20+
const sum = nums[i] + nums[left] + nums[right];
21+
22+
if (sum === 0) {
23+
res.push([nums[i], nums[left], nums[right]]);
24+
25+
while (nums[left] === nums[left + 1]) {
26+
left++;
27+
}
28+
29+
while (nums[right] === nums[right - 1]) {
30+
right++;
31+
}
32+
33+
left++;
34+
right--;
35+
36+
continue;
37+
}
38+
39+
if (sum < 0) {
40+
left++;
41+
42+
continue;
43+
}
44+
45+
right--;
46+
}
47+
}
48+
49+
return res;
50+
}
51+
52+
const tc1 = threeSum([-1, 0, 1, 2, -1, -4]); // [[-1,-1,2],[-1,0,1]]
53+
console.info("🚀 : tolluset.ts:39: tc1=", tc1);
54+
55+
const tc2 = threeSum([0, 0, 0]); // [[0,0,0]]
56+
console.info("🚀 : tolluset.ts:42: tc2=", tc2);
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
2+
// T.C: O(N)
3+
// S.C: O(1)
4+
function maxProfit(prices: number[]): number {
5+
let min = prices[0];
6+
let max = prices[0];
7+
let candidate = prices[0];
8+
9+
for (let i = 1; i < prices.length; i++) {
10+
if (prices[i] < candidate) {
11+
candidate = prices[i];
12+
} else if (prices[i] - candidate > max - min) {
13+
min = candidate;
14+
max = prices[i];
15+
}
16+
}
17+
18+
return max - min;
19+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
'''
2+
풀이
3+
- 주어진 배열 prices를 한 번 탐색합니다.
4+
5+
- prices[i]가 이전에 저장한 buy_price보다 낮을 경우,
6+
maximum profit이 증가할 가능성이 있습니다.
7+
따라서 buy_price와 sell_price를 prices[i]로 바꿔줍니다.
8+
9+
- prices[i]가 이전에 저장한 sell_price보다 높은 경우,
10+
현재 buy_price로 지금까지 기록한 profit보다 더 높은 이익을 내게 됩니다.
11+
따라서 sell_price를 prices[i]로 바꿔주고 결과값을 갱신합니다.
12+
13+
Big O
14+
- N: 배열 prices의 크기
15+
16+
- Time complexity: O(N)
17+
- 배열의 크기 N이 증가함에 따라 실행 시간도 선형적으로 증가합니다.
18+
19+
- Space complexity: O(1)
20+
- 배열의 크기 N이 증가하여도 사용하는 메모리 공간은 일정합니다.
21+
'''
22+
23+
class Solution:
24+
def maxProfit(self, prices: List[int]) -> int:
25+
res = 0
26+
27+
buy_price = prices[0]
28+
sell_price = prices[0]
29+
30+
for i in range(1, len(prices)):
31+
curr_price = prices[i]
32+
33+
if buy_price > curr_price:
34+
buy_price = curr_price
35+
sell_price = curr_price
36+
elif sell_price < curr_price:
37+
sell_price = curr_price
38+
res = max(res, sell_price - buy_price)
39+
40+
return res
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// 시간복잡도: O(n)
2+
// 공간복잡도: O(1)
3+
/**
4+
* @param {number[]} prices
5+
* @return {number}
6+
*/
7+
var maxProfit = function(prices) {
8+
if (!prices || !prices.length) return 0
9+
10+
let maxBenefit = 0;
11+
let buyPrice = Infinity;
12+
13+
for (let i = 0 ; i < prices.length ; i++) {
14+
buyPrice = Math.min(buyPrice, prices[i]);
15+
maxBenefit = Math.max(maxBenefit, prices[i] - buyPrice)
16+
}
17+
18+
19+
return maxBenefit
20+
};
21+
22+
console.log(maxProfit([7,1,5,3,6,4]))
23+
console.log(maxProfit([7,6,4,3,1]))
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# 시간복잡도: O(N)
2+
# 공간복잡도: O(1)
3+
class Solution:
4+
def maxProfit(self, prices: List[int]) -> int:
5+
6+
answer = 0
7+
cur = float(inf)
8+
for price in prices:
9+
if cur < price:
10+
answer = max(answer, price - cur)
11+
12+
if price < cur:
13+
cur = price
14+
15+
return answer

0 commit comments

Comments
 (0)