Skip to content

Commit e504685

Browse files
Merge branch 'DaleStudy:main' into week3
2 parents 5160fc3 + ca8b8a5 commit e504685

File tree

2,432 files changed

+86652
-1181
lines changed

Some content is hidden

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

2,432 files changed

+86652
-1181
lines changed

.github/pull_request_template.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212

1313
## 작성자 체크 리스트
1414

15-
- [ ] 우측 메뉴에서 PR을 **Projects**에 추가해주세요.
1615
- [ ] **Projects**의 오른쪽 버튼(▼)을 눌러 확장한 뒤, **Week**를 현재 주차로 설정해주세요.
1716
- [ ] 문제를 모두 푸시면 프로젝트에서 **Status**`In Review`로 설정해주세요.
1817
- [ ] 코드 검토자 1분 이상으로부터 승인을 받으셨다면 PR을 병합해주세요.

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/HISEHOONAN.swift

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
//
2+
// 241.swift
3+
// Algorithm
4+
//
5+
// Created by 안세훈 on 4/8/25.
6+
//
7+
8+
//3Sum
9+
class Solution { //정렬 + two pointer
10+
func threeSum(_ nums: [Int]) -> [[Int]] {
11+
let nums = nums.sorted() //배열을 오름차순으로 정렬
12+
var result: [[Int]] = [] // 결과를 저장할 배열.
13+
14+
for i in 0..<nums.count { // i를 0번째 배열부터 순회.
15+
if i > 0 && nums[i] == nums[i - 1] {
16+
continue
17+
}
18+
19+
var left = i + 1 //left는 i+1번째 인덱스
20+
var right = nums.count - 1 //right는 배열의 끝번째 인덱스
21+
22+
while left < right {
23+
let sum = nums[i] + nums[left] + nums[right]
24+
25+
if sum == 0 {
26+
result.append([nums[i], nums[left], nums[right]])
27+
28+
// 중복 제거
29+
while left < right && nums[left] == nums[left + 1] {
30+
left += 1
31+
}
32+
while left < right && nums[right] == nums[right - 1] {
33+
right -= 1
34+
}
35+
36+
left += 1
37+
right -= 1
38+
} else if sum < 0 {
39+
left += 1
40+
} else {
41+
right -= 1
42+
}
43+
}
44+
}
45+
46+
return result
47+
}
48+
}

3sum/HoonDongKang.ts

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* [Problem]: [15] 3Sum
3+
* (https://leetcode.com/problems/3sum/description/)
4+
*/
5+
6+
function threeSum(nums: number[]): number[][] {
7+
//시간 복잡도: O(n^2)
8+
//공간 복잡도: O(1)
9+
function pointerFunc(nums: number[]): number[][] {
10+
const result: number[][] = [];
11+
nums.sort((a, b) => a - b);
12+
13+
for (let i = 0; i < nums.length; i++) {
14+
if (i > 0 && nums[i] === nums[i - 1]) continue;
15+
let left = i + 1;
16+
let right = nums.length - 1;
17+
18+
while (left < right) {
19+
const sum = nums[i] + nums[left] + nums[right];
20+
if (sum === 0) {
21+
result.push([nums[i], nums[left], nums[right]]);
22+
23+
while (left < right && nums[left] === nums[left + 1]) left++;
24+
while (left < right && nums[right] === nums[right - 1]) right--;
25+
26+
left++;
27+
right--;
28+
} else if (sum < 0) {
29+
left++;
30+
} else {
31+
right--;
32+
}
33+
}
34+
}
35+
return result;
36+
}
37+
38+
return pointerFunc(nums);
39+
}

3sum/JEONGBEOMKO.java

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

3sum/Jeehay28.ts

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
// Approach 3
2+
// 🗓️ 2025-04-12
3+
// ⏳ Time Complexity: O(n log n) + O(n^2) = O(n^2)
4+
// 💾 Space Complexity: O(1) (excluding output)
5+
6+
function threeSum(nums: number[]): number[][] {
7+
8+
nums.sort((a, b) => a - b); // O(n log n)
9+
let result: number[][] = [];
10+
11+
for (let i = 0; i < nums.length; i++) {
12+
13+
if (i > 0 && nums[i - 1] == nums[i]) continue; // skip duplicate i
14+
15+
let low = i + 1, high = nums.length - 1;
16+
// two-pointer scan (low and high) -> takes up to O(n) time per iteration
17+
while (low < high) {
18+
const threeSum = nums[i] + nums[low] + nums[high];
19+
if (threeSum < 0) {
20+
low += 1;
21+
} else if (threeSum > 0) {
22+
high -= 1;
23+
} else {
24+
result.push([nums[i], nums[low], nums[high]]);
25+
26+
while (low < high && nums[low] === nums[low + 1]) low += 1 // skip duplicate low
27+
while (low < high && nums[high] === nums[high - 1]) high -= 1 // skip duplicate high
28+
29+
low += 1;
30+
high -= 1;
31+
32+
}
33+
}
34+
}
35+
return result
36+
}
37+
38+
39+
// Approach 2
40+
// 🗓️ 2025-04-11
41+
// ❌ Time Limit Exceeded 313 / 314 testcases passed
42+
// ⏳ Time Complexity: O(n^2)
43+
// 💾 Space Complexity: O(n^2)
44+
45+
// function threeSum(nums: number[]): number[][] {
46+
// const result: number[][] = [];
47+
// const triplets = new Set<string>();
48+
49+
// for (let i = 0; i < nums.length - 2; i++) {
50+
// const seen = new Set<number>();
51+
// for (let j = i + 1; j < nums.length; j++) {
52+
// const twoSum = nums[i] + nums[j];
53+
// if (seen.has(-twoSum)) {
54+
// const triplet = [nums[i], nums[j], -twoSum].sort((a, b) => a - b); // O(log 3) = O(1)
55+
// const key = triplet.join(",");
56+
// if (!triplets.has(key)) {
57+
// triplets.add(key);
58+
// result.push(triplet);
59+
// }
60+
// }
61+
// seen.add(nums[j]);
62+
// }
63+
// }
64+
// return result;
65+
// }
66+
67+
68+
// Approach 1
69+
// 🗓️ 2025-04-11
70+
// ❌ Time Limit Exceeded!
71+
// ⏳ Time Complexity: O(n^3)
72+
// 💾 Space Complexity: O(n^2)
73+
74+
// function threeSum(nums: number[]): number[][] {
75+
76+
// let triplets = new Set<string>();
77+
// let result: number[][] = [];
78+
79+
// // const set = new Set();
80+
// // set.add([1, 2, 3]);
81+
// // set.add([1, 2, 3]);
82+
// // console.log(set); // contains BOTH arrays
83+
// // Set(2) { [ 1, 2, 3 ], [ 1, 2, 3 ] }
84+
85+
// for (let i = 0; i < nums.length - 2; i++) {
86+
// for (let j = i + 1; j < nums.length - 1; j++) {
87+
// for (let k = j + 1; k < nums.length; k++) {
88+
// if (nums[i] + nums[j] + nums[k] === 0) {
89+
// const triplet = [nums[i], nums[j], nums[k]].sort((a, b) => a - b);
90+
// const key = triplet.join(",");
91+
// if (!triplets.has(key)) {
92+
// triplets.add(key);
93+
// result.push(triplet)
94+
// }
95+
// }
96+
// }
97+
// }
98+
// }
99+
100+
// return result;
101+
// };

3sum/JustHm.swift

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution {
2+
// time: O(n2) space: O(n)..?
3+
func threeSum(_ nums: [Int]) -> [[Int]] {
4+
let nums = nums.sorted() // hashmap 방식으로는 안될거 같아 정렬후 순차탐색 하기
5+
6+
var answer = Set<[Int]>() // 중복 제거를 위해 Set으로 선언
7+
for i in nums.indices {
8+
var left = i + 1
9+
var right = nums.count - 1
10+
while left < right {
11+
let result = nums[left] + nums[right] + nums[i]
12+
if result == 0 {
13+
answer.insert([nums[i], nums[left], nums[right]])
14+
// 포인터 옮겨주고 더 검사하기
15+
right -= 1
16+
left += 1
17+
}
18+
else if result > 0 {
19+
right -= 1
20+
}
21+
else {
22+
left += 1
23+
}
24+
}
25+
}
26+
return Array(answer)
27+
}
28+
}

3sum/KwonNayeon.py

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,35 @@
33
1. 3 <= nums.length <= 3000
44
2. -10^5 <= nums[i] <= 10^5
55
6-
Time Complexity:
7-
- O(n^2) (정렬은 O(n log n), 이중 반복문은 O(n^2))
8-
Space Complexity:
9-
- O(n) (결과 리스트)
6+
Time Complexity: O(n^2)
7+
- 정렬은 O(n log n), 이중 반복문은 O(n^2)
8+
Space Complexity: O(n)
9+
- 결과 리스트를 저장하는 데 필요한 공간
10+
11+
풀이 방법:
12+
- 투 포인터를 활용하여 합이 0이 되는 세 수 조합 찾기
13+
- 배열 정렬: 투 포인터 사용 + 중복 처리 용이
14+
- for 루프: 첫 번째 숫자 선택 (len(nums)-2까지)
15+
- 중복된 첫 번째 숫자 건너뛰기
16+
- left, right 포인터 설정
17+
- while 루프: 두 포인터가 교차하지 않아야 함
18+
- sum = nums[i] + nums[left] + nums[right] 계산
19+
- sum == 0: 결과 추가, 중복 건너뛰기, 양쪽 포인터 이동
20+
- sum < 0: left 증가 (더 큰 값 필요)
21+
- sum > 0: right 감소 (더 작은 값 필요)
22+
- 최종 결과 반환
1023
"""
24+
# Brute-force: three nested loops → O(n^3)
25+
# Optimized: sort + two pointer → O(n^2)
1126

1227
class Solution:
1328
def threeSum(self, nums: List[int]) -> List[List[int]]:
29+
# Step 1: Sort the array
30+
# Step 2: Fix one number using for loop
31+
# Step 3: Use two pointers to find two other numbers
32+
# - if sum == 0: valid triplet
33+
# - if sum < 0: move left pointer
34+
# - if sum > 0: move right pointer
1435
nums.sort()
1536
result = []
1637

0 commit comments

Comments
 (0)