Skip to content

Commit 2a9a6f8

Browse files
authored
Merge branch 'DaleStudy:main' into main
2 parents 3251a99 + c5ed177 commit 2a9a6f8

92 files changed

Lines changed: 2696 additions & 23 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

3sum/YOOHYOJEONG.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# https://leetcode.com/problems/3sum
2+
3+
class Solution(object):
4+
def threeSum(self, nums):
5+
nums.sort()
6+
result = []
7+
8+
for i in range(len(nums) - 2):
9+
10+
if i > 0 and nums[i] == nums[i - 1]:
11+
continue
12+
13+
left = i + 1
14+
right = len(nums) - 1
15+
16+
while left < right:
17+
total = nums[i] + nums[left] + nums[right]
18+
19+
if total < 0:
20+
left += 1
21+
22+
elif total > 0:
23+
right -= 1
24+
25+
else:
26+
result.append([nums[i], nums[left], nums[right]])
27+
28+
while left < right and nums[left] == nums[left + 1]:
29+
left += 1
30+
31+
while left < right and nums[right] == nums[right - 1]:
32+
right -= 1
33+
34+
left += 1
35+
right -= 1
36+
37+
return result

3sum/Yu-Won.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* 문제: https://leetcode.com/problems/3sum/description/
3+
*
4+
* 요구사항:
5+
* nums: number[]가 주어질 때 3개의 합이 0이되는 배열을 리턴한다.
6+
*
7+
* * */
8+
9+
const threeSum = (nums) => {
10+
let result = [];
11+
12+
nums.sort((a,b) => a-b);
13+
14+
for(let i = 0; i <nums.length-2; i++) {
15+
if(i > 0 && nums[i] === nums[i-1]) continue;
16+
17+
if(nums[i] > 0) break;
18+
19+
let left= i+1;
20+
let right = nums.length -1;
21+
22+
while(left < right) {
23+
let sum = nums[i] + nums[left] + nums[right];
24+
25+
if(sum === 0) {
26+
result.push([nums[i], nums[left], nums[right]]);
27+
28+
while(left < right && nums[left] === nums[left+1]) left++;
29+
while(left < right && nums[right] === nums[right-1]) right++;
30+
left++;
31+
right--;
32+
} else if (sum <0) {
33+
left++;
34+
} else {
35+
right--;
36+
}
37+
}
38+
}
39+
return result;
40+
}

3sum/gcount85.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
"""
2+
# Intuition
3+
처음에는 1주차의 Two Sum 문제 풀이를 응용하여, 배열 순회 + 해시 테이블 만들어 값 찾기를 시도했으나
4+
정렬 + 투포인터 풀이가 더 빠르므로 그렇게 제출했습니다.
5+
6+
# Approach
7+
nums 배열을 순회하면서 -nums[i]를 합으로 하는 두 수를 나머지 배열 부분에서 찾는다.
8+
찾을 때는 정렬 & 투포인터를 활용하여 중복을 건너 뛰는 방식으로 속도를 높인다.
9+
10+
11+
# Complexity
12+
- Time complexity: 정렬 + 투포인터 이중 반복으로 O(N^2)
13+
14+
- Space complexity: 정렬 하는데에 O(N) , answer 배열 생성하는데에 O(M)
15+
"""
16+
17+
18+
class Solution:
19+
def threeSum(self, nums: list[int]) -> list[list[int]]:
20+
nums.sort() # O(NlogN)
21+
n = len(nums)
22+
answer = []
23+
24+
for i in range(n - 2): # 이중 반복문 O(N^2)
25+
# 중복 제거
26+
if i > 0 and nums[i] == nums[i - 1]:
27+
continue
28+
29+
# nums[i]가 0보다 크면 뒤도 다 양수라 종료 가능
30+
if nums[i] > 0:
31+
break
32+
33+
left, right = i + 1, n - 1
34+
35+
while left < right:
36+
total = nums[i] + nums[left] + nums[right]
37+
38+
if total == 0:
39+
answer.append([nums[i], nums[left], nums[right]])
40+
left += 1
41+
right -= 1
42+
43+
# left/right 중복 제거
44+
while left < right and nums[left] == nums[left - 1]:
45+
left += 1
46+
while left < right and nums[right] == nums[right + 1]:
47+
right -= 1
48+
49+
elif total < 0:
50+
left += 1
51+
else:
52+
right -= 1
53+
54+
return answer

3sum/hwi-middle.cpp

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class Solution {
2+
public:
3+
vector<vector<int>> threeSum(vector<int>& nums) {
4+
vector<vector<int>> res;
5+
6+
sort(nums.begin(), nums.end());
7+
8+
for (int i = 0; i < nums.size() && nums[i] <= 0; ++i)
9+
{
10+
if (i != 0 && nums[i - 1] == nums[i])
11+
{
12+
continue;
13+
}
14+
15+
int l = i + 1;
16+
int r = nums.size() - 1;
17+
while (l < r)
18+
{
19+
int sum = nums[i] + nums[l] + nums[r];
20+
if (sum < 0)
21+
{
22+
++l;
23+
}
24+
else if (sum > 0)
25+
{
26+
--r;
27+
}
28+
else
29+
{
30+
res.push_back({nums[i], nums[l++], nums[r--]});
31+
while (l < r && nums[l] == nums[l - 1])
32+
{
33+
++l;
34+
}
35+
}
36+
}
37+
}
38+
39+
return res;
40+
}
41+
};

3sum/hyeri0903.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
from itertools import combinations
2+
3+
class Solution:
4+
def threeSum(self, nums: List[int]) -> List[List[int]]:
5+
"""
6+
time complexity : O(n^2)
7+
space complexity : O(1)
8+
"""
9+
answer = []
10+
nums.sort()
11+
n = len(nums)
12+
13+
for i in range(n):
14+
#skipped if nums[i] == nums[i-1] to avoid duplicate triplets
15+
if i > 0 and nums[i] == nums[i-1]:
16+
continue
17+
18+
#search with two pointer
19+
left, right = i+1, n-1
20+
21+
while left < right:
22+
total = nums[left] + nums[i] + nums[right]
23+
if total == 0:
24+
answer.append([nums[left], nums[i], nums[right]])
25+
26+
#move the pointers past duplicates
27+
while left < right and nums[left] == nums[left+1]:
28+
left += 1
29+
while left < right and nums[right] == nums[right-1]:
30+
right -= 1
31+
32+
left += 1
33+
right -= 1
34+
elif total < 0:
35+
left += 1
36+
else:
37+
right -= 1
38+
39+
return answer

3sum/junzero741.ts

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// TC: O(n^2)
2+
// SC: O(logn)
3+
function threeSum(nums: number[]): number[][] {
4+
5+
nums.sort((a,b) => a-b);
6+
const result: number[][] = []
7+
8+
for(let i = 0 ; i < nums.length; i++) {
9+
let left = i+1;
10+
let right = nums.length-1;
11+
12+
while(left < right) {
13+
if(i > 0 && nums[i] === nums[i-1]) {
14+
break;
15+
}
16+
17+
const sum = nums[i] + nums[left] + nums[right];
18+
if(sum > 0) {
19+
right--;
20+
continue;
21+
}
22+
if(sum < 0) {
23+
left++;
24+
continue;
25+
}
26+
if(sum === 0) {
27+
const triplet: number[] = [nums[i], nums[left], nums[right]];
28+
result.push(triplet);
29+
30+
while(left < right && nums[left] === nums[left+1]) {
31+
left++;
32+
}
33+
while(left < right && nums[right] === nums[right-1]) {
34+
right--;
35+
}
36+
37+
left++;
38+
right--;
39+
}
40+
}
41+
42+
}
43+
44+
return result;
45+
};

3sum/kangdaia.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
class Solution:
2+
def threeSum(self, nums: list[int]) -> list[list[int]]:
3+
"""
4+
nums에서 세 숫자를 골라 합이 0이 되는 조합을 구하는 함수
5+
세 숫자는 서로 다른 인덱스에 위치해야 함. 중복된 조합은 포함하지 않아야 함.
6+
7+
방법
8+
1. brute force. 세 숫자를 모두 조합하여 합이 0이 되는지 확인. O(n^3) 시간복잡도 -> 너무 오래 걸림!
9+
2. 첫번째 값을 고정하고 나머지 두개의 합을 two sum 문제에서 해결한 것 처럼 dict에 저장하여 찾기. O(n^2) 시간복잡도, O(n) 공간복잡도
10+
-> 중복된 조합을 걸러내는 과정이 필요함
11+
3. 정렬을 해서, 첫번째 값을 고정하고, 나머지 두개의 합이 첫번째 값의 음수가 되는 경우를 찾음 - 포인터 방식.
12+
-> O(n^2) 시간복잡도, O(1) 공간복잡도. 2번 방법보다 정렬을 하지 않으니 효율적
13+
4. 3번 방법에 시간을 줄일 수 있는 예외 케이스 혹은 조건을 찾아 빠르게 종료하기
14+
- 첫번째 값이 양수인 경우, 나머지 두개의 합이 음수가 될 수 없으므로 종료
15+
- 첫번째 값이 이전 값과 같은 경우, 중복된 조합이 되니 건너뛰기
16+
- append 값을 찾은 후에 j+1, k-1을 하면서 중복된 값이 아닐때까지 이동하기
17+
18+
Args:
19+
nums (list[int]): 정렬되지 않은 정수목록
20+
21+
Returns:
22+
list[list[int]]: 합이 0이 되는 세 숫자의 조합 목록
23+
"""
24+
answer = []
25+
s_nums = sorted(nums)
26+
n = len(s_nums)
27+
for i in range(n - 2):
28+
x = s_nums[i]
29+
if i > 0 and x == s_nums[i - 1]:
30+
continue
31+
if x > 0:
32+
break
33+
j, k = i + 1, n - 1
34+
while j < k:
35+
y, z = s_nums[j], s_nums[k]
36+
total = x + y + z
37+
if total == 0:
38+
answer.append([x, y, z])
39+
j += 1
40+
k -= 1
41+
while j < k and s_nums[j] == s_nums[j - 1]:
42+
j += 1
43+
while j < k and s_nums[k] == s_nums[k + 1]:
44+
k -= 1
45+
elif total < 0:
46+
j += 1
47+
else:
48+
k -= 1
49+
return answer

3sum/mrlee7.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def threeSum(self, nums: List[int]) -> List[List[int]]:
6+
result: List[List[int]] = []
7+
nums.sort()
8+
9+
for i in range(len(nums) - 2):
10+
if i > 0 and nums[i] == nums[i - 1]:
11+
continue
12+
13+
left = i + 1
14+
right = len(nums) - 1
15+
16+
while left < right:
17+
total = nums[i] + nums[left] + nums[right]
18+
19+
if total == 0:
20+
result.append([nums[i], nums[left], nums[right]])
21+
left += 1
22+
right -= 1
23+
24+
while left < right and nums[left] == nums[left - 1]:
25+
left += 1
26+
while left < right and nums[right] == nums[right + 1]:
27+
right -= 1
28+
29+
elif total < 0:
30+
left += 1
31+
else:
32+
right -= 1
33+
34+
return result

3sum/sadie100.ts

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/*
2+
배열을 정렬한 뒤 엘리먼트 하나를 고정하고, 해당 엘리먼트보다 큰 범위에서 투 포인터 순회로 합이 -{엘리먼트값} 이 되는 쌍을 찾는 로직을 모든 배열 엘리먼트에 순회하며 적용한다
3+
4+
시간복잡도 : O(N^2)
5+
=> 엘리먼트 고정 순회 n * 투 포인터 순회 n
6+
7+
공간복잡도 : O(N)
8+
=> 정렬된 배열
9+
*/
10+
11+
function threeSum(nums: number[]): number[][] {
12+
const sortedNums = nums.sort((a, b) => a - b)
13+
const result = []
14+
let beforeIVal
15+
16+
for (let i = 0; i < nums.length; i++) {
17+
const idxVal = sortedNums[i]
18+
if (beforeIVal !== undefined && beforeIVal === idxVal) {
19+
continue
20+
}
21+
beforeIVal = idxVal
22+
const shouldBe = -idxVal
23+
let start = i + 1
24+
let end = nums.length - 1
25+
26+
while (start < end) {
27+
const startVal = sortedNums[start]
28+
const endVal = sortedNums[end]
29+
const value = startVal + endVal
30+
if (value === shouldBe) {
31+
result.push([idxVal, startVal, endVal])
32+
start += 1
33+
end -= 1
34+
while (startVal === sortedNums[start]) {
35+
start += 1
36+
}
37+
while (endVal === sortedNums[end]) {
38+
end -= 1
39+
}
40+
} else if (value > shouldBe) {
41+
end -= 1
42+
} else {
43+
start += 1
44+
}
45+
}
46+
}
47+
48+
return result
49+
}

0 commit comments

Comments
 (0)