Skip to content

Commit 00b6cde

Browse files
authored
Merge branch 'DaleStudy:main' into main
2 parents 3427d40 + 4c8b68f commit 00b6cde

File tree

168 files changed

+6334
-25
lines changed

Some content is hidden

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

168 files changed

+6334
-25
lines changed

3sum/Chaedie.py

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
"""
2+
첫번째 풀이 -> 달레의 코드 풀이
3+
1) sort와 two pointer를 활용한 풀이
4+
2) has_set 을 활용한 중복 제거
5+
6+
두번째 풀이 -> Neetcode 풀이
7+
1) sort와 two pointer를 활용한 풀이
8+
2) while loop 를 활용한 중복 제거
9+
10+
Time: O(n^2) = O(n) * O(n)
11+
Space: O(n)
12+
"""
13+
14+
15+
class Solution:
16+
def threeSum(self, nums: List[int]) -> List[List[int]]:
17+
nums.sort()
18+
res = set()
19+
n = len(nums)
20+
21+
for i in range(n):
22+
l, r = i + 1, n - 1
23+
while l < r:
24+
summ = nums[i] + nums[l] + nums[r]
25+
if summ < 0:
26+
l += 1
27+
elif summ > 0:
28+
r -= 1
29+
else:
30+
res.add((nums[i], nums[l], nums[r]))
31+
l += 1
32+
return list(res)
33+
34+
35+
class Solution:
36+
def threeSum(self, nums: List[int]) -> List[List[int]]:
37+
nums.sort()
38+
res = []
39+
n = len(nums)
40+
41+
for i in range(n):
42+
l, r = i + 1, n - 1
43+
44+
if i > 0 and nums[i] == nums[i - 1]:
45+
continue
46+
47+
while l < r:
48+
summ = nums[i] + nums[l] + nums[r]
49+
if summ < 0:
50+
l += 1
51+
elif summ > 0:
52+
r -= 1
53+
else:
54+
res.append([nums[i], nums[l], nums[r]])
55+
l += 1
56+
while nums[l] == nums[l - 1] and l < r:
57+
l += 1
58+
59+
return res

3sum/EcoFriendlyAppleSu.kt

+104
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
package leetcode_study
2+
3+
/**
4+
* 주어진 배열의 세 원소의 합이 0인 경우를 구하는 문제. (세 개의 값의 결과는 중복되지 않음)
5+
*
6+
* 주어진 조건
7+
* 3 <= nums.length <= 3000
8+
* -105 <= nums[i] <= 105
9+
*/
10+
11+
/**
12+
* case01. 조합을 사용한 풀이.
13+
* 시간 초과 발생 이유
14+
* -> 모든 가능한 세 개의 조합을 생성하기 때문에 발생.
15+
* 시간 복잡도:
16+
* -> 세 개의 조합 생성 과정: O(n * (n-1) * (n-2)) / 3. 최악의 경우 n = 3000, 4.5 억개 조합 생성
17+
* -> 세 개의 조합 결과 sorting 과정: O(klogk). k = 3
18+
* -> 결과값을 필터링해 합이 0인 배열을 필터하는 과정: O(n)
19+
* 나머지 연산이 세 개의 조합 생성 과정에 영향을 받아 계산 횟수 증가.
20+
*
21+
* 공간 복잡도:
22+
* -> 각 조합을 모두 저장: O(n^3)
23+
*/
24+
fun threeSumUseCombination(nums: IntArray): List<List<Int>> {
25+
// 결과를 담을 Set 자료구조
26+
val processResult = mutableSetOf<List<Int>>()
27+
28+
// 주어진 배열의 크기를 담는 변수
29+
val maxNumber = nums.size
30+
31+
// 조합 배열의 크기
32+
val givenSize = 3
33+
34+
// 나타낼 인덱스를 구하는 배열 초기화
35+
val indices = IntArray(givenSize)
36+
for (i in 0 until givenSize) {
37+
indices[i] = i
38+
}
39+
40+
while (indices[givenSize - 1] < maxNumber) {
41+
processResult.add(indices.map { nums[it] }.sorted())
42+
var i = givenSize - 1
43+
44+
while (i >= 0 && indices[i] == i + maxNumber - givenSize) {
45+
i--
46+
}
47+
48+
if (i >= 0) {
49+
indices[i]++
50+
for (j in i + 1 until givenSize) {
51+
indices[j] = indices[j-1] + 1
52+
}
53+
} else break
54+
}
55+
56+
return processResult.filter { it.sum() == 0 }
57+
}
58+
59+
/**
60+
* case02. 투 포인터를 사용한 풀이
61+
* 조합을 사용한 풀이와 달리 시간 초과가 발생하지 않음. O(n^3)의 시간 복잡도를 O(n^2)으로 줄임
62+
*
63+
* 시간 복잡도:
64+
* -> 주어진 숫자 배열 오름차순으로 정렬: O(nlogn)
65+
* -> 세 개의 숫자를 더하는 로직
66+
* -> 외부 반복문을 통해 주어진 배열 전체 조회: O(n)
67+
* -> 내부 반복문을 통해 start to last index 순회: O(n)
68+
* -> O(n^2)
69+
* ∴ O(nlogn) + O(n^2) => O(n^2)
70+
*
71+
* 공간 복잡도:
72+
* -> 주어진 숫자 배열의 정렬을 담는 공간 필요: O(n)
73+
*/
74+
fun threeSum(nums: IntArray): List<List<Int>> {
75+
val processResult = mutableListOf<List<Int>>()
76+
val sortedNums = nums.sorted()
77+
78+
for (i in sortedNums.indices) {
79+
if (i > 0 && sortedNums[i] == sortedNums[i-1]) continue
80+
81+
var startIndex = i + 1
82+
var lastIndex = sortedNums.size - 1
83+
84+
while (startIndex < lastIndex) {
85+
val sum = sortedNums[i] + sortedNums[startIndex] + sortedNums[lastIndex]
86+
when {
87+
sum == 0 -> {
88+
processResult.add(listOf(sortedNums[i], sortedNums[startIndex], sortedNums[lastIndex]))
89+
while (startIndex < lastIndex && sortedNums[startIndex] == sortedNums[startIndex + 1]) startIndex++
90+
while (startIndex < lastIndex && sortedNums[lastIndex] == sortedNums[lastIndex - 1]) lastIndex--
91+
startIndex++
92+
lastIndex--
93+
}
94+
sum < 0 -> {
95+
startIndex++
96+
}
97+
else -> {
98+
lastIndex--
99+
}
100+
}
101+
}
102+
}
103+
return processResult
104+
}

3sum/Gotprgmer.java

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// 이전에 투포인터를 활용하여 시도했지만 중복된 값들을 처리하는데 어려움이 있었습니다.
2+
// 그래서 해답을 보았고 새로운 방법으로 풀어보았습니다.
3+
// 서로 다른 i와 j 인덱스를 2중 for문으로 진행하면서
4+
// i와 j사이 수들을 set으로 관리합니다.
5+
// set에 -nums[i]-nums[j]가 존재하면 결과 리스트에 추가합니다.
6+
// 시간복잡도 : O(N^2)
7+
// 공간복잡도 : O(N)
8+
class SolutionGotprgmer {
9+
public List<List<Integer>> threeSum(int[] nums) {
10+
// 결과를 저장할 리스트
11+
List<List<Integer>> result = new ArrayList<>();
12+
Set<Integer> set;
13+
Set<List<Integer>> resultSet = new HashSet<>();
14+
List<Integer> numList;
15+
16+
17+
// 리스트 정렬
18+
Arrays.sort(nums);
19+
for(int i=0;i<nums.length-2;i++){
20+
if (i > 0 && nums[i - 1] == nums[i]) continue;
21+
22+
set = new HashSet<>();
23+
for(int j=i+1;j<nums.length;j++){
24+
int checkNum = nums[i]+nums[j];
25+
if(set.contains(-checkNum)){
26+
numList = new ArrayList<>(Arrays.asList(nums[i], -checkNum, nums[j]));
27+
if(!resultSet.contains(numList)){
28+
result.add(numList);
29+
resultSet.add(numList);
30+
}
31+
}
32+
set.add(nums[j]);
33+
}
34+
}
35+
return result;
36+
}
37+
}

3sum/HodaeSsi.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution:
2+
def threeSum(self, nums: List[int]) -> List[List[int]]:
3+
answerSet = set()
4+
nums.sort()
5+
6+
for i in range(len(nums) - 2):
7+
leftIdx = i + 1
8+
rightIdx = len(nums) - 1
9+
while leftIdx < rightIdx:
10+
sum = nums[i] + nums[leftIdx] + nums[rightIdx]
11+
if sum < 0:
12+
leftIdx += 1
13+
elif sum > 0:
14+
rightIdx -= 1
15+
else:
16+
answerSet.add((nums[i], nums[leftIdx], nums[rightIdx]))
17+
leftIdx = leftIdx + 1
18+
rightIdx = rightIdx - 1
19+
20+
return list(answerSet)
21+

3sum/Jeehay28.js

+86
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number[][]}
4+
*/
5+
6+
7+
// Time Complexity: O(n^2)
8+
// Space Complexity: O(n^2)
9+
10+
var threeSum = function (nums) {
11+
12+
const sorted = [...nums].sort((a, b) => a - b);
13+
14+
let result = [];
15+
16+
// Loop through the array and pick each number as the first number for the triplet
17+
for (let i = 0; i < sorted.length - 2; i++) {
18+
19+
// skip duplicate values for sorted[middle]
20+
if(i > 0 && sorted[i - 1] === sorted[i]) {
21+
continue;
22+
}
23+
24+
let left = i + 1; // Left pointer starts right after the current middle
25+
let right = sorted.length - 1; // Right pointer starts at the last element
26+
27+
while (left < right) {
28+
const sum = sorted[i] + sorted[left] + sorted[right];
29+
30+
if (sum === 0) {
31+
result.push([sorted[left], sorted[i], sorted[right]]);
32+
33+
// skip duplicates for sorted[left] and sorted[right]
34+
while(left < right && sorted[left] === sorted[left + 1]){
35+
left += 1; // Move left pointer to the right to skip duplicate values
36+
}
37+
38+
while(left < right && sorted[right] === sorted[right - 1]) {
39+
right -= 1; // Move right pointer to the left to skip duplicate values
40+
}
41+
42+
left += 1;
43+
right -= 1;
44+
45+
} else if (sum > 0) {
46+
right -= 1;
47+
48+
} else {
49+
left += 1
50+
}
51+
}
52+
}
53+
54+
return result;
55+
56+
};
57+
58+
59+
// var threeSum = function (nums) {
60+
61+
// i != j, i != k, and j != k can be interpreted as i < j < k
62+
63+
// three nested loops
64+
// time complexity of O(n³)
65+
// Time Limit Exceeded
66+
67+
// let result = [];
68+
69+
// for (let i = 0; i < nums.length - 2; i++) {
70+
// for (let j = i + 1; j < nums.length - 1; j++) {
71+
// for (let k = j + 1; k < nums.length; k++) {
72+
// if (nums[i] + nums[j] + nums[k] === 0) {
73+
// const str = [nums[i], nums[j], nums[k]].sort((a, b) => a - b).join(",")
74+
// result.push(str)
75+
// }
76+
// }
77+
// }
78+
79+
// }
80+
81+
// result = [... new Set(result)].map(str => str.split(",").map(str => +str))
82+
83+
// return result;
84+
85+
// }
86+

0 commit comments

Comments
 (0)