Skip to content

Commit 9c9b03b

Browse files
dohee789dohee789
authored andcommitted
Merge remote-tracking branch 'origin/main'
2 parents 0b7dff6 + 0ddba79 commit 9c9b03b

File tree

370 files changed

+10588
-132
lines changed

Some content is hidden

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

370 files changed

+10588
-132
lines changed

3sum/Geegong.java

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import java.util.*;
2+
3+
public class Geegong {
4+
5+
/**
6+
* Time complexity : O(n^2)
7+
* space complexity : O(n^2)
8+
* @param nums
9+
* @return
10+
*/
11+
public List<List<Integer>> threeSum(int[] nums) {
12+
13+
// 중복되는 값은 없어야 하기에 HashSet 으로 result
14+
HashSet<List<Integer>> result = new HashSet<>();
15+
16+
// Key : 배열 원소 , value : List<String> 인덱스들
17+
// elementMap 은 two pointer 의 값을 더한 값에서 0이 되기 위한 요소를 찾기위해 사용될 것임
18+
// tc : O(n)
19+
Map<Integer, List<Integer>> elementMap = new HashMap<>();
20+
for (int index = 0; index<nums.length; index++) {
21+
int value = nums[index];
22+
if (elementMap.containsKey(value)) {
23+
List<Integer> indices = elementMap.get(value);
24+
indices.add(index);
25+
elementMap.put(value, indices);
26+
} else {
27+
List<Integer> newIndices = new ArrayList<>();
28+
newIndices.add(index);
29+
elementMap.put(value, newIndices);
30+
}
31+
}
32+
33+
// leftIndex : 0에서 부터 시작하는 index
34+
// rightIndex : nums.length - 1에서부터 감소하는 index
35+
// leftIndex > rightIndex 되는 순간까지만 for문을 돌 것이다.
36+
// tc : O(N^2 / 2)
37+
for (int leftIndex=0; leftIndex < nums.length; leftIndex++) {
38+
for (int rightIndex=nums.length - 1; rightIndex >= 0; rightIndex--) {
39+
40+
if (leftIndex >= rightIndex) {
41+
break;
42+
}
43+
44+
45+
int leftValue = nums[leftIndex];
46+
int rightValue = nums[rightIndex];
47+
48+
int neededValueToZero = -leftValue - rightValue;
49+
if (elementMap.containsKey(neededValueToZero)) {
50+
// elementMap의 value 가 leftIndex, rightIndex 은 아닌지 확인
51+
52+
List<Integer> indices = elementMap.get(neededValueToZero);
53+
// zero 를 만들 수 있는 세번쨰 인덱스가 있는지 확인
54+
int thirdIndex = findThirdIndexToBeZero(leftIndex, rightIndex, indices);
55+
if (-1 != thirdIndex) {
56+
List<Integer> newOne = new ArrayList<>();
57+
newOne.add(nums[leftIndex]);
58+
newOne.add(nums[rightIndex]);
59+
newOne.add(nums[thirdIndex]);
60+
result.add(newOne.stream().sorted().toList());
61+
}
62+
63+
}
64+
65+
}
66+
}
67+
68+
return result.stream().toList();
69+
70+
}
71+
72+
public int findThirdIndexToBeZero(int leftIndex, int rightIndex, List<Integer> indices) {
73+
for (int index : indices) {
74+
if (index != leftIndex && index != rightIndex) {
75+
return index;
76+
}
77+
}
78+
79+
return -1;
80+
}
81+
}
82+

3sum/bskkimm.py

Whitespace-only changes.

3sum/chordpli.py

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

3sum/chrisjune.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def threeSum(self, nums: List[int]) -> List[List[int]]:
6+
if len(nums) >= 3 and set(nums) == set([0]):
7+
return [[0, 0, 0]]
8+
triplets = set()
9+
for i in range(len(nums) - 2):
10+
seen = set()
11+
for j in range(i + 1, len(nums)):
12+
f = -(nums[i] + nums[j])
13+
if f in seen:
14+
triplet = [nums[i], nums[j], f]
15+
triplets.add(tuple(sorted(triplet)))
16+
seen.add(nums[j])
17+
return list(triplets)

3sum/delight010.swift

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution {
2+
func threeSum(_ nums: [Int]) -> [[Int]] {
3+
let nums = nums.sorted()
4+
var answer: Set<[Int]> = []
5+
for (index, num) in nums.enumerated() {
6+
var leftIndex = index + 1
7+
var rightIndex = nums.endIndex - 1
8+
while leftIndex < rightIndex {
9+
let sum = num + nums[leftIndex] + nums[rightIndex]
10+
if sum == 0 {
11+
answer.insert([num, nums[leftIndex], nums[rightIndex]])
12+
leftIndex += 1
13+
rightIndex -= 1
14+
} else if sum < 0 {
15+
leftIndex += 1
16+
} else if sum > 0 {
17+
rightIndex -= 1
18+
}
19+
}
20+
}
21+
22+
return Array(answer)
23+
}
24+
}
25+

3sum/grapefruitgreentealoe.js

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
//1.dfs로 풀기 : 시간초과 남
2+
3+
4+
/**
5+
* @param {number[]} nums
6+
* @return {number[][]}
7+
*/
8+
var threeSum = function(nums) {
9+
/*
10+
arr: 현재 고정 배열을 뜻함. dfs가 돌때마다 변경됨.
11+
start: 끝난 index. arr와 마찬가지로 이것은 for문안에서 변경될 예정.
12+
dep: dep은 현재 dfs의 dep+1을 해주면 됨.
13+
*/
14+
const numsLength = nums.length
15+
if(numsLength ==3 && nums.reduce((a,b)=>a+b,0) == 0) return [nums]
16+
17+
const ret = []
18+
const seen = new Set();
19+
nums.sort((a, b) => a - b);
20+
21+
function dfs(arr,start,dep){
22+
if(dep == 3) {
23+
if(arr.length !==3) return
24+
const arrTotal = arr.reduce((a,b)=>a+b,0);
25+
if(arrTotal == 0){
26+
const string = [...arr].sort((a,b)=>a-b).join(',')
27+
if(!seen.has(string)){
28+
seen.add(string)
29+
ret.push(arr)
30+
}
31+
}
32+
return
33+
}
34+
//만약 start가 0이 되면, i를 감소시켜야하고, 새로운 배열을 추가해야한다. 기존의 배열에 넣어주는게 아니다.
35+
36+
//끝점을 증가시키면서 진행해야함. 현재 고정 arr에 끝점 그 앞의 idx부터 진행해서 0까지 감소시키면서 dfs를 돌리면 된다.
37+
//idx가 i-1부터이므로, i는 최소 1이어야 가능하다.
38+
for(let idx = start; idx<numsLength; idx++){
39+
// currArr.push([...arr,nums[idx]])
40+
//현재 i에 대한 현재 currArr를 만들어준다.
41+
//만들어준 각 Arr에 대해서, 다시 dfs로 들어가서, 각 배열의 내부의 합이 0인지 확인하고,
42+
//현재 배열에 대한 set에 대해서 중복이 되는 것은 없는지 확인하면서 넣어준다.
43+
dfs([...arr,nums[idx]],idx+1,dep+1)
44+
}}
45+
dfs([],0,0)
46+
//마지막에 set으로 triples의 중복을 제거해줘야한다.
47+
48+
return ret
49+
};
50+
51+
/*
52+
시간복잡도:
53+
nums.sort((a, b) => a - b): 배열 정렬에 O(NlogN)
54+
55+
N개 숫자 중 3개 선택하는 조합 수 N(N−1)(N−2)/6
56+
정확히 알 수는 없지만,
57+
58+
N^3 이상으로 보임.
59+
60+
공간복잡도 : O(N^3) => seen 때문.
61+
62+
*/
63+
64+
//2. 투포인터로 풀기
65+
66+
/*
67+
우선 내가 문제에 대한 이해가 틀렸다. 숫자의 순서가 다르다고 하더라도, 같은 숫자의 조합을 가지고 있다면 안된다.
68+
값이 원하는 값보다 작으면 오른쪽 값을 옮기고, 크면 왼쪽 값을 옮기는 투포인터 전략을 취해보았다.
69+
70+
*/
71+
72+
/**
73+
* @param {number[]} nums
74+
* @return {number[][]}
75+
*/
76+
var threeSum = function(nums) {
77+
const triplets = []
78+
nums.sort((a,b)=>a-b)
79+
for(let i =0;i<nums.length -2 ;i++){
80+
if (i > 0 && nums[i] === nums[i - 1]) continue;
81+
let low = i+1
82+
,high = nums.length -1
83+
84+
while(low < high){
85+
const three_sum = nums[i] + nums[low] + nums[high]
86+
if(three_sum<0){
87+
low +=1
88+
}
89+
else if(three_sum >0){
90+
high -=1
91+
}
92+
else{
93+
triplets.push([nums[i],nums[low],nums[high]])
94+
while (low < high && nums[low] === nums[low + 1]) low++;
95+
while (low < high && nums[high] === nums[high - 1]) high--;
96+
low = low+1
97+
high = high -1
98+
}
99+
}
100+
}
101+
return triplets
102+
};

3sum/hi-rachel.py

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,64 @@
1-
# O(n^2) time, O(n) space
1+
"""
2+
https://leetcode.com/problems/3sum/
3+
4+
문제 설명:
5+
정렬되지 않은 정수 배열 nums가 주어질 때,
6+
세 수의 합이 0이 되는 모든 유니크한 triplet을 찾는 문제.
7+
8+
조건:
9+
- 중복 조합은 허용되지 않음.
10+
- 예: [-1, 0, 1]과 [0, -1, 1]은 같은 조합이므로 하나만 포함.
11+
12+
풀이 전략:
13+
1. 배열을 정렬한다.
14+
2. 첫 번째 수를 고정한 뒤, 나머지 두 수를 투포인터로 탐색한다.
15+
- 합이 0보다 작으면 left를 증가
16+
- 합이 0보다 크면 right를 감소
17+
- 합이 0이면 정답에 추가, 중복 방지 처리도 함께 수행
18+
19+
TC: O(n^2), 정렬 O(n log n) + 투포인터 O(n^2)
20+
SC: O(1), 출력 공간 result 제외
21+
"""
22+
23+
from typing import List
24+
25+
26+
class Solution:
27+
def threeSum(self, nums: List[int]) -> List[List[int]]:
28+
nums.sort()
29+
result = []
30+
31+
for i in range(len(nums) - 2):
32+
if i > 0 and nums[i] == nums[i - 1]:
33+
continue # 중복 제거
34+
35+
left, right = i + 1, len(nums) - 1
36+
37+
while left < right:
38+
total = nums[i] + nums[left] + nums[right]
39+
# 조건 만족시 정답에 추가
40+
if total == 0:
41+
result.append([nums[i], nums[left], nums[right]])
42+
# 같은 값을 가진 left가 여러 개 있다면, 중복 건너뜀
43+
while left < right and nums[left] == nums[left + 1]:
44+
left += 1
45+
# 같은 값을 가진 right가 여러 개 있다면, 중복 건너뜀
46+
while left < right and nums[right] == nums[right - 1]:
47+
right -= 1
48+
left += 1
49+
right -= 1
50+
# 총합이 0보다 작으면, 더 큰 수가 필요하니까 left를 오른쪽으로 이동
51+
elif total < 0:
52+
left += 1
53+
# 총합이 0보다 크면, 더 작은 수가 필요하니까 right를 왼쪽으로 이동
54+
else:
55+
right -= 1
256

57+
return result
58+
59+
60+
61+
# O(n^2) time, O(n) space
362
class Solution:
463
def threeSum(self, nums: List[int]) -> List[List[int]]:
564
triplets = set()

3sum/hj4645.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution:
2+
def threeSum(self, nums: List[int]) -> List[List[int]]:
3+
nums.sort() # 배열 정렬해서 중복 처리와 투 포인터에 유리하게 만듦
4+
n = len(nums)
5+
answer = []
6+
7+
for i in range(n - 2):
8+
# i가 0이 아니면서 이전 값과 같으면 중복 방지를 위해 건너뜀
9+
if i > 0 and nums[i] == nums[i - 1]:
10+
continue
11+
12+
left, right = i + 1, n - 1
13+
14+
while left < right:
15+
total = nums[i] + nums[left] + nums[right]
16+
17+
if total == 0:
18+
answer.append([nums[i], nums[left], nums[right]])
19+
20+
# left와 right가 가리키는 값이 중복이면 넘어감
21+
while left < right and nums[left] == nums[left + 1]:
22+
left += 1
23+
while left < right and nums[right] == nums[right - 1]:
24+
right -= 1
25+
26+
left += 1
27+
right -= 1
28+
elif total < 0:
29+
left += 1
30+
else:
31+
right -= 1
32+
33+
return answer

3sum/hoyeongkwak.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/*
2+
Time Complexity : O(n^2)
3+
Space Complexity : O(1)
4+
*/
5+
class Solution {
6+
public List<List<Integer>> threeSum(int[] nums) {
7+
List<List<Integer>> result = new ArrayList<>();
8+
Arrays.sort(nums);
9+
10+
for (int i = 0; i < nums.length - 2; i++) {
11+
if (i > 0 && nums[i] == nums[i - 1]) continue;
12+
int low = i + 1;
13+
int high = nums.length - 1;
14+
while (low < high) {
15+
int threeSum = nums[i] + nums[low] + nums[high];
16+
if (threeSum < 0) {
17+
low = low + 1;
18+
} else if (threeSum > 0) {
19+
high = high - 1;
20+
} else {
21+
result.add(Arrays.asList(nums[i], nums[low], nums[high]));
22+
while (low < high && nums[low] == nums[low + 1]) low++;
23+
while (low < high && nums[high] == nums[high - 1]) high--;
24+
low = low + 1;
25+
high = high - 1;
26+
}
27+
}
28+
}
29+
30+
return result;
31+
}
32+
}

0 commit comments

Comments
 (0)