forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGeegong.java
More file actions
82 lines (65 loc) Β· 2.85 KB
/
Geegong.java
File metadata and controls
82 lines (65 loc) Β· 2.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import java.util.*;
public class Geegong {
/**
* Time complexity : O(n^2)
* space complexity : O(n^2)
* @param nums
* @return
*/
public List<List<Integer>> threeSum(int[] nums) {
// μ€λ³΅λλ κ°μ μμ΄μΌ νκΈ°μ HashSet μΌλ‘ result
HashSet<List<Integer>> result = new HashSet<>();
// Key : λ°°μ΄ μμ , value : List<String> μΈλ±μ€λ€
// elementMap μ two pointer μ κ°μ λν κ°μμ 0μ΄ λκΈ° μν μμλ₯Ό μ°ΎκΈ°μν΄ μ¬μ©λ κ²μ
// tc : O(n)
Map<Integer, List<Integer>> elementMap = new HashMap<>();
for (int index = 0; index<nums.length; index++) {
int value = nums[index];
if (elementMap.containsKey(value)) {
List<Integer> indices = elementMap.get(value);
indices.add(index);
elementMap.put(value, indices);
} else {
List<Integer> newIndices = new ArrayList<>();
newIndices.add(index);
elementMap.put(value, newIndices);
}
}
// leftIndex : 0μμ λΆν° μμνλ index
// rightIndex : nums.length - 1μμλΆν° κ°μνλ index
// leftIndex > rightIndex λλ μκ°κΉμ§λ§ forλ¬Έμ λ κ²μ΄λ€.
// tc : O(N^2 / 2)
for (int leftIndex=0; leftIndex < nums.length; leftIndex++) {
for (int rightIndex=nums.length - 1; rightIndex >= 0; rightIndex--) {
if (leftIndex >= rightIndex) {
break;
}
int leftValue = nums[leftIndex];
int rightValue = nums[rightIndex];
int neededValueToZero = -leftValue - rightValue;
if (elementMap.containsKey(neededValueToZero)) {
// elementMapμ value κ° leftIndex, rightIndex μ μλμ§ νμΈ
List<Integer> indices = elementMap.get(neededValueToZero);
// zero λ₯Ό λ§λ€ μ μλ μΈλ²μ¨° μΈλ±μ€κ° μλμ§ νμΈ
int thirdIndex = findThirdIndexToBeZero(leftIndex, rightIndex, indices);
if (-1 != thirdIndex) {
List<Integer> newOne = new ArrayList<>();
newOne.add(nums[leftIndex]);
newOne.add(nums[rightIndex]);
newOne.add(nums[thirdIndex]);
result.add(newOne.stream().sorted().toList());
}
}
}
}
return result.stream().toList();
}
public int findThirdIndexToBeZero(int leftIndex, int rightIndex, List<Integer> indices) {
for (int index : indices) {
if (index != leftIndex && index != rightIndex) {
return index;
}
}
return -1;
}
}