Skip to content

Commit 9cac4c2

Browse files
authored
Merge branch 'DaleStudy:main' into main
2 parents 7ffb3cd + b2d8c3d commit 9cac4c2

125 files changed

Lines changed: 3509 additions & 30 deletions

File tree

Some content is hidden

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

3sum/DaleSeo.rs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// TC: O(n^2)
2+
// SC: O(1)
3+
impl Solution {
4+
pub fn three_sum(mut nums: Vec<i32>) -> Vec<Vec<i32>> {
5+
nums.sort_unstable();
6+
let n = nums.len();
7+
let mut triplets = Vec::new();
8+
9+
for i in 0..n {
10+
if i > 0 && nums[i] == nums[i - 1] {
11+
continue;
12+
}
13+
14+
let (mut low, mut high) = (i + 1, n - 1);
15+
while low < high {
16+
let three_sum = nums[i] + nums[low] + nums[high];
17+
if three_sum < 0 {
18+
low += 1;
19+
} else if three_sum > 0 {
20+
high -= 1;
21+
} else {
22+
triplets.push(vec![nums[i], nums[low], nums[high]]);
23+
low += 1;
24+
high -= 1;
25+
while low < high && nums[low] == nums[low - 1] {
26+
low += 1;
27+
}
28+
while low < high && nums[high] == nums[high + 1] {
29+
high -= 1;
30+
}
31+
}
32+
}
33+
}
34+
35+
triplets
36+
}
37+
}

3sum/ICE0208.java

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import java.util.*;
2+
3+
class Solution {
4+
public List<List<Integer>> threeSum(int[] nums) {
5+
/*
6+
* 세 수의 합이 0이 되는 조합을 찾는다.
7+
*
8+
* nums[i]를 하나 고정하면,
9+
* 나머지 두 수를 찾는 Two Sum 문제로 바꿀 수 있다.
10+
*
11+
* seen에는 현재 i 기준으로 지나온 값들을 저장한다.
12+
* target이 seen에 있으면 nums[i] + target + nums[j] = 0 이다.
13+
*
14+
*
15+
* 시간 복잡도: O(n^2)
16+
* 공간 복잡도: O(n)
17+
*/
18+
19+
Arrays.sort(nums);
20+
21+
List<List<Integer>> answer = new ArrayList<>();
22+
23+
for (int i = 0; i < nums.length; i++) {
24+
// 같은 기준값은 한 번만 사용
25+
if (i > 0 && nums[i] == nums[i - 1]) {
26+
continue;
27+
}
28+
29+
// 기준값이 양수면 합이 0이 될 수 없음
30+
if (nums[i] > 0) {
31+
break;
32+
}
33+
34+
Set<Integer> seen = new HashSet<>();
35+
36+
for (int j = i + 1; j < nums.length; j++) {
37+
int target = -nums[i] - nums[j];
38+
39+
if (seen.contains(target)) {
40+
answer.add(Arrays.asList(nums[i], target, nums[j]));
41+
42+
// 같은 nums[j]는 중복 조합을 만들 수 있으므로 스킵
43+
while (j + 1 < nums.length && nums[j] == nums[j + 1]) {
44+
j++;
45+
}
46+
}
47+
48+
seen.add(nums[j]);
49+
}
50+
}
51+
52+
return answer;
53+
}
54+
}

3sum/JeonJe.java

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

3sum/JinuCheon.py

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
# brute force 로 풀어본 답안. O(n3) 다. 역시 timeout.
2+
# dic, set 자료형 익히기 겸 해봤다. 파이썬 편하다 최고.
3+
class Solution:
4+
def threeSum(self, nums: list[int]) -> list[list[int]]:
5+
n = len(nums)
6+
result = set()
7+
8+
for i in range(n):
9+
for j in range(n):
10+
for k in range(n):
11+
if (i == j or j == k or i == k):
12+
continue
13+
if (nums[i] + nums[j] + nums[k] == 0):
14+
result.add(tuple(sorted([nums[i], nums[j], nums[k]])))
15+
16+
return list(result)
17+
18+
# LLM 에게 힌트 얻어서 진행.
19+
# i != j, i != k, j != k 조건 때문에 정렬을 하면 안된다고 착각하고 있었다. 사실 고정된 순서는 중요하지 않음.
20+
# 정렬을 진행하고, two pointer 로 진행.
21+
# 통과!
22+
class Solution2:
23+
def threeSum(self, nums: list[int]) -> list[list[int]]:
24+
# 정렬
25+
nums.sort()
26+
n = len(nums)
27+
result = set()
28+
29+
for i in range(n):
30+
# i 자리 중복 skip (이전 원소와 같으면 건너뜀)
31+
if i > 0 and nums[i] == nums[i - 1]:
32+
continue
33+
34+
# i + left + right === 0 이 되어야 함.
35+
left = i + 1
36+
right = n - 1
37+
38+
while left < right:
39+
if nums[left] + nums[right] == -nums[i]:
40+
result.add(tuple([nums[i], nums[left], nums[right]]))
41+
left += 1
42+
right -= 1
43+
44+
elif nums[left] + nums[right] < -nums[i]:
45+
left += 1
46+
else:
47+
right -= 1
48+
49+
return list(result)
50+
51+
# LLM의 피드백.
52+
# 중복을 스킵하는 효율적인 방법이 있었음.
53+
class Solution:
54+
def threeSum(self, nums: list[int]) -> list[list[int]]:
55+
nums.sort()
56+
n = len(nums)
57+
result = []
58+
59+
for i in range(n):
60+
if i > 0 and nums[i] == nums[i - 1]:
61+
continue
62+
63+
if nums[i] > 0:
64+
break
65+
66+
left, right = i + 1, n - 1
67+
target = -nums[i]
68+
69+
while left < right:
70+
s = nums[left] + nums[right]
71+
if s == target:
72+
result.append([nums[i], nums[left], nums[right]])
73+
left += 1
74+
right -= 1
75+
76+
# left, right 자리도 중복 skip
77+
while left < right and nums[left] == nums[left - 1]:
78+
left += 1
79+
while left < right and nums[right] == nums[right + 1]:
80+
right -= 1
81+
82+
elif s < target:
83+
left += 1
84+
else:
85+
right -= 1
86+
87+
return result

3sum/Yiseull.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution:
2+
def threeSum(self, nums: list[int]) -> list[list[int]]:
3+
answer = set()
4+
5+
nums = sorted(nums)
6+
7+
n = len(nums)
8+
for i in range(n - 2):
9+
if nums[i] > 0:
10+
break
11+
12+
if i > 0 and nums[i] == nums[i - 1]:
13+
continue
14+
15+
left, right = i + 1, n - 1
16+
while left < right:
17+
threeSum = nums[i] + nums[left] + nums[right]
18+
if threeSum < 0:
19+
left += 1
20+
elif threeSum == 0:
21+
answer.add((nums[i], nums[left], nums[right]))
22+
left += 1
23+
right -= 1
24+
else:
25+
right -= 1
26+
27+
return list(answer)

3sum/Zero-1016.ts

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* 시간 복잡도 O(n²)
3+
* 공간 복잡도 O(log n)
4+
*
5+
* 접근: 오름차순 정렬 + 투 포인터
6+
* - 기준 인덱스 i를 고정하고, left = i + 1, right = 끝에서 탐색
7+
* - 정렬된 상태에서 같은 값을 건너뛰는 방식으로 중복 제거 (Set 불필요)
8+
*/
9+
function threeSum(nums: number[]): number[][] {
10+
const result: number[][] = [];
11+
nums.sort((a, b) => a - b); // 오름차순 정렬
12+
13+
for (let i = 0; i < nums.length - 2; i++) {
14+
// 기준 숫자가 이전과 같으면 동일한 조합이 나오므로 건너뜀
15+
if (i > 0 && nums[i] === nums[i - 1]) continue;
16+
17+
// 최적화: 기준 숫자가 양수면 뒤의 숫자들도 모두 양수 → 합이 0 불가능
18+
if (nums[i] > 0) break;
19+
20+
let left = i + 1;
21+
let right = nums.length - 1;
22+
23+
while (left < right) {
24+
const sum = nums[i] + nums[left] + nums[right];
25+
26+
if (sum === 0) {
27+
result.push([nums[i], nums[left], nums[right]]);
28+
29+
while (left < right && nums[left] === nums[left + 1]) left++;
30+
while (left < right && nums[right] === nums[right - 1]) right--;
31+
32+
left++;
33+
right--;
34+
} else if (sum < 0) {
35+
left++;
36+
} else {
37+
right--;
38+
}
39+
}
40+
}
41+
42+
return result;
43+
}

3sum/daehyun99.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class Solution:
2+
def threeSum(self, nums: List[int]) -> List[List[int]]:
3+
res = []
4+
nums.sort()
5+
6+
for i, a in enumerate(nums):
7+
if a > 0:
8+
break
9+
if i > 0 and a == nums[i-1]:
10+
continue
11+
12+
l, r = i+1, len(nums) - 1
13+
while l < r:
14+
total = a + nums[l] + nums[r]
15+
if total > 0:
16+
r -= 1
17+
elif total < 0:
18+
l += 1
19+
else:
20+
res.append([a, nums[l], nums[r]])
21+
l += 1
22+
r -= 1
23+
while nums[l] == nums[l - 1] and l < r:
24+
l += 1
25+
return res
26+
27+
"""from collections import Counter
28+
29+
class Solution:
30+
def threeSum(self, nums: list[int]) -> list[list[int]]:
31+
counts = Counter(nums)
32+
result: set[tuple[int, int, int]] = set()
33+
34+
for i in range(len(nums) - 2):
35+
for j in range(i + 1, len(nums) - 1):
36+
adding = -(nums[i] + nums[j])
37+
38+
if adding not in counts:
39+
continue
40+
41+
local_counts = Counter([nums[i], nums[j], adding])
42+
43+
for num, count in local_counts.items():
44+
if counts[num] < count:
45+
break
46+
else:
47+
triplet = tuple(sorted([nums[i], nums[j], adding]))
48+
result.add(triplet)
49+
50+
return [list(triplet) for triplet in result]
51+
"""

0 commit comments

Comments
 (0)