Skip to content

Commit 7da8e35

Browse files
authored
Merge branch 'DaleStudy:main' into main
2 parents 369a555 + 3ff060e commit 7da8e35

48 files changed

Lines changed: 1406 additions & 0 deletions

Some content is hidden

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

3sum/Cyjin-jani.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// ! 풀다가 막혀서 AI의 도움(힌트)을 받아 완성한 코드입니다..
2+
3+
// tc: o(n^2)
4+
// sc: o(n)
5+
const threeSum = function (nums) {
6+
const answer = [];
7+
8+
// 먼저 오름차순 정렬하기
9+
const sortedArr = nums.sort((a, b) => a - b);
10+
11+
for (let i = 0; i < sortedArr.length; i++) {
12+
if (i > 0 && sortedArr[i] === sortedArr[i - 1]) continue;
13+
14+
let left = i + 1;
15+
let right = sortedArr.length - 1;
16+
17+
while (left < right) {
18+
const sum = sortedArr[i] + sortedArr[left] + sortedArr[right];
19+
20+
if (sum === 0) {
21+
answer.push([sortedArr[i], sortedArr[left], sortedArr[right]]);
22+
23+
// 중복 처리
24+
// left가 가리키는 숫자가 이전 숫자와 똑같다면 계속 패스
25+
while (left < right && sortedArr[left] === sortedArr[left + 1]) {
26+
left++;
27+
}
28+
// right가 가리키는 숫자가 이전 숫자와 똑같다면 계속 패스
29+
while (left < right && sortedArr[right] === sortedArr[right - 1]) {
30+
right--;
31+
}
32+
// 똑같은 숫자들을 다 건너뛰었으니, 새로운 숫자로 넘어감
33+
left++;
34+
right--;
35+
} else if (sum < 0) {
36+
// 0보다 작으면 left를 키움 (오름차순 정렬이기 때문)
37+
left++;
38+
} else {
39+
right--;
40+
}
41+
}
42+
}
43+
44+
return answer;
45+
};

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/dohyeon2.java

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import java.util.Arrays;
2+
import java.util.ArrayList;
3+
import java.util.List;
4+
5+
class Solution {
6+
// TC: O(n^2)
7+
// SC: O(n^2)
8+
public List<List<Integer>> threeSum(int[] nums) {
9+
List<List<Integer>> answer = new ArrayList<List<Integer>>();
10+
11+
// Sort the array to use two-pointer technique.
12+
Arrays.sort(nums);
13+
14+
// Exclude the last two elements from the loop
15+
// since the two pointers are involved in the iteration.
16+
for (int i = 0; i < nums.length - 2; i++) {
17+
if (i - 1 >= 0 && nums[i] == nums[i - 1]) {
18+
// Skip if this number is the same as the previous one,
19+
// so that we can avoid duplicate triplets.
20+
continue;
21+
}
22+
23+
int left = i + 1;
24+
int right = nums.length - 1;
25+
26+
while (left < right) {
27+
int sum = nums[i] + nums[left] + nums[right];
28+
if (sum == 0) {
29+
ArrayList<Integer> list = new ArrayList<>(
30+
Arrays.asList(nums[i], nums[left], nums[right]));
31+
answer.add(list);
32+
33+
// According to the problem, we need to avoid duplicate triplets.
34+
// Therefore, this loop is needed.
35+
while (left < right && nums[left] == nums[left + 1]) {
36+
left++;
37+
}
38+
while (left < right && nums[right] == nums[right - 1]) {
39+
right--;
40+
}
41+
42+
left++;
43+
right--;
44+
} else if (sum < 0) {
45+
left++;
46+
} else {
47+
right--;
48+
}
49+
}
50+
51+
}
52+
53+
return answer;
54+
}
55+
}

3sum/jiji-hoon96.ts

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
// time limit 실패
2+
3+
// function threeSum(nums: number[]): number[][] {
4+
// const result: number[][] = [];
5+
// for (let i = 0; i < nums.length; i++) {
6+
// for (let j = 1; j < nums.length; j++) {
7+
// for (let k = 2; k < nums.length; k++) {
8+
// if (
9+
// i !== j &&
10+
// j !== k &&
11+
// i !== k &&
12+
// nums[i] + nums[j] + nums[k] === 0
13+
// ) {
14+
// const hasArray = result.some(
15+
// (item) =>
16+
// JSON.stringify([...item].sort((a, b) => a - b)) ===
17+
// JSON.stringify([nums[i], nums[j], nums[k]].sort((a, b) => a - b)),
18+
// );
19+
// if (!hasArray) {
20+
// result.push([nums[i], nums[j], nums[k]]);
21+
// }
22+
// }
23+
// }
24+
// }
25+
// }
26+
// return result;
27+
// }
28+
29+
function threeSum(nums: number[]): number[][] {
30+
const result: number[][] = [];
31+
nums.sort((a, b) => a - b);
32+
33+
for (let i = 0; i < nums.length - 2; i++) {
34+
if (i > 0 && nums[i] === nums[i - 1]) continue;
35+
36+
let left = i + 1;
37+
let right = nums.length - 1;
38+
39+
while (left < right) {
40+
const sum = nums[i] + nums[left] + nums[right];
41+
42+
if (sum === 0) {
43+
result.push([nums[i], nums[left], nums[right]]);
44+
while (left < right && nums[left] === nums[left + 1]) left++;
45+
while (left < right && nums[right] === nums[right - 1]) right--;
46+
left++;
47+
right--;
48+
} else if (sum < 0) {
49+
left++;
50+
} else {
51+
right--;
52+
}
53+
}
54+
}
55+
return result;
56+
}
57+
58+
threeSum([-1, 0, 1, 2, -1, -4]); // [[-1,-1,2],[-1,0,1]]
59+
threeSum([0, 1, 1]); // []
60+
threeSum([0, 0, 0]); // [[0,0,0]]
61+
threeSum([
62+
12, 5, -12, 4, -11, 11, 2, 7, 2, -5, -14, -3, -3, 3, 2, -10, 9, -15, 2, 14,
63+
-3, -15, -3, -14, -1, -7, 11, -4, -11, 12, -15, -14, 2, 10, -2, -1, 6, 7, 13,
64+
-15, -13, 6, -10, -9, -14, 7, -12, 3, -1, 5, 2, 11, 6, 14, 12, -10, 14, 0, -7,
65+
11, -10, -7, 4, -1, -12, -13, 13, 1, 9, 3, 1, 3, -5, 6, 9, -4, -2, 5, 14, 12,
66+
-5, -6, 1, 8, -15, -10, 5, -15, -2, 5, 3, 3, 13, -8, -13, 8, -5, 8, -6, 11,
67+
-12, 3, 0, -2, -6, -14, 2, 0, 6, 1, -11, 9, 2, -3, -6, 3, 3, -15, -5, -14, 5,
68+
13, -4, -4, -10, -10, 11,
69+
]); // [[-15,1,14],[-15,2,13],[-15,3,12],[-15,4,11],[-15,5,10],[-15,6,9],[-15,7,8],[-14,0,14],[-14,1,13],[-14,2,12],[-14,3,11],[-14,4,10],[-14,5,9],[-14,6,8],[-14,7,7],[-13,-1,14],[-13,0,13],[-13,1,12],[-13,2,11],[-13,3,10],[-13,4,9],[-13,5,8],[-13,6,7],[-12,-2,14],[-12,-1,13],[-12,0,12],[-12,1,11],[-12,2,10],[-12,3,9],[-12,4,8],[-12,5,7],[-12,6,6],[-11,-3,14],[-11,-2,13],[-11,-1,12],[-11,0,11],[-11,1,10],[-11,2,9],[-11,3,8],[-11,4,7],[-11,5,6],[-10,-4,14],[-10,-3,13],[-10,-2,12],[-10,-1,11],[-10,0,10],[-10,1,9],[-10,2,8],[-10,3,7],[-10,4,6],[-10,5,5],[-9,-5,14],[-9,-4,13],[-9,-3,12],[-9,-2,11],[-9,-1,10],[-9,0,9],[-9,1,8],[-9,2,7],[-9,3,6],[-9,4,5],[-8,-6,14],[-8,-5,13],[-8,-4,12],[-8,-3,11],[-8,-2,10],[-8,-1,9],[-8,0,8],[-8,1,7],[-8,2,6],[-8,3,5],[-8,4,4],[-7,-7,14],[-7,-6,13],[-7,-5,12],[-7,-4,11],[-7,-3,10],[-7,-2,9],[-7,-1,8],[-7,0,7],[-7,1,6],[-7,2,5],[-7,3,4],[-6,-6,12],[-6,-5,11],[-6,-4,10],[-6,-3,9],[-6,-2,8],[-6,-1,7],[-6,0,6],[-6,1,5],[-6,2,4],[-6,3,3],[-5,-5,10],[-5,-4,9],[-5,-3,8...

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/liza0525.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,39 @@ def threeSum(self, nums: List[int]) -> List[List[int]]:
3636
results.add((nums[i], nums[left], nums[right]))
3737
left, right = left + 1, right - 1
3838
return list(results)
39+
40+
41+
# 7기 풀이
42+
# 시간 복잡도: O(n^2)
43+
# - 배열 정렬: O(n log n)
44+
# - for문과 while문을 이용한 이중 loop문으로 탐색: O(n^2)
45+
# - 전체 시간 복잡도는 O(n^2)
46+
# 공간 복잡도: O(1)
47+
# - 결과 저장 공간은 output이므로 제외 (변수 이름: results)
48+
class Solution:
49+
def threeSum(self, nums: List[int]) -> List[List[int]]:
50+
nums.sort() # 정렬을 한 번 한 후
51+
results = set()
52+
53+
# for 문과 투포인터를 이용해 문제를 푼다.
54+
for i in range(len(nums) - 2):
55+
# i번째와 i - 1 번째 값이 같은 경우에는 이미 이전 loop에서 계산했기 때문에 다음 루프로 넘긴다
56+
if i > 0 and nums[i] == nums[i - 1]:
57+
continue
58+
59+
# 포인터 지정
60+
left, right = i + 1, len(nums) - 1
61+
while left < right:
62+
result = nums[i] + nums[left] + nums[right]
63+
if result < 0:
64+
# 합이 0보다 작다면 요소의 값을 올려야 하기 때문에 left를 올린다. (nums는 정렬이 된 상태)
65+
left += 1
66+
elif result > 0:
67+
# 합이 0보다 크다면 요소의 값을 줄여야 하기 때문에 right를 내린다. (nums는 정렬이 된 상태)
68+
right -= 1
69+
else:
70+
# 합이 0이면 결과 저장 후, 포인터를 조정하여 다음 triplet 세트를 찾는다.
71+
results.add((nums[i], nums[left], nums[right]))
72+
left, right = left + 1, right - 1
73+
74+
return list(results)

3sum/sangbeenmoon.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# time : O(n^2)
2+
# space : O(n)
3+
class Solution:
4+
def threeSum(self, nums: list[int]) -> list[list[int]]:
5+
nums.sort()
6+
answer = []
7+
8+
for i, num in enumerate(nums):
9+
# 중복 제거
10+
if i > 0 and nums[i] == nums[i-1]:
11+
continue
12+
13+
target = num * -1
14+
15+
visited = dict() # 중복 제거
16+
left = i + 1
17+
right = len(nums) - 1
18+
19+
while left < right:
20+
sum_ = nums[left] + nums[right]
21+
if sum_ < target:
22+
left = left + 1
23+
elif sum_ > target:
24+
right = right - 1
25+
else:
26+
if nums[left] not in visited: # 중복 제거
27+
answer.append([num, nums[left], nums[right]])
28+
visited[nums[left]] = True
29+
30+
left = left + 1
31+
right = right - 1
32+
return answer

3sum/tedkimdev.go

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// TC: O(n^2)
2+
// SC: O(m)
3+
func threeSum(nums []int) [][]int {
4+
result := make(map[[3]int]struct{})
5+
6+
sort.Ints(nums)
7+
8+
// target value = nums[k]
9+
for k := 0; k < len(nums); k++ {
10+
left := 0
11+
if k == left {
12+
left = 1
13+
}
14+
right := len(nums) - 1
15+
if k == right {
16+
right = len(nums) - 2
17+
}
18+
19+
target := nums[k]
20+
for left < right {
21+
sum := nums[left] + nums[right] + target
22+
if sum == 0 {
23+
if left > k {
24+
result[[3]int{nums[k], nums[left], nums[right]}] = struct{}{}
25+
} else if left < k && k < right {
26+
result[[3]int{nums[left], nums[k], nums[right]}] = struct{}{}
27+
} else if k > right {
28+
result[[3]int{nums[left], nums[right], nums[k]}] = struct{}{}
29+
}
30+
}
31+
if sum < 0 {
32+
left++
33+
if k == left {
34+
left++
35+
}
36+
} else {
37+
right--
38+
if k == right {
39+
right--
40+
}
41+
}
42+
}
43+
44+
}
45+
46+
filteredResult := [][]int{}
47+
for k, _ := range result {
48+
filteredResult = append(filteredResult, k[0:len(k)])
49+
}
50+
51+
return result.keys()
52+
}

0 commit comments

Comments
 (0)