forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjaejeong1.java
More file actions
34 lines (33 loc) ยท 1.43 KB
/
jaejeong1.java
File metadata and controls
34 lines (33 loc) ยท 1.43 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
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
// ์ ์ฒด ์๊ฐ ๋ณต์ก๋: O(N2), ๊ณต๊ฐ ๋ณต์ก๋: O(N)
// ์ ๋ ฌ: ์๊ฐ ๋ณต์ก๋: O(N log N)
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<>();
// x ํ๋ ์ก์๋๊ณ , ํฌํฌ์ธํฐ ์ฌ์ฉํด์ y + z ๊ฐ -x ๋ณด๋ค ํฌ๋ฉด z ๋ฅผ - 1, ์ ์ผ๋ฉด y ๋ฅผ + 1, y์ z๊ฐ ๋ง๋๋ฉด break, y + z ๊ฐ -x ์ ๊ฐ์ผ๋ฉด ์ ๋ต
// 0 ๋ณด๋ค ํฐ ์ผ์ด์ค๋ ๋ ํ์๊ฐ ์์
for (int i = 0; i < nums.length && nums[i] <= 0; ++i) {
// ์๊ฐ ๋ณต์ก๋: O(N)
if (i == 0 || nums[i - 1] != nums[i]) {
findThreeSum(nums, i, result);
}
}
return result;
}
void findThreeSum(int[] nums, int i, List<List<Integer>> result) {
// ์๊ฐ ๋ณต์ก๋: O(N), ๊ณต๊ฐ ๋ณต์ก๋: O(3N) = O(N)
int left = i + 1, right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum < 0) {
++left;
} else if (sum > 0) {
--right;
} else {
// ์ ๋ต ์ผ์ด์ค ์ฐพ์์ ๊ฒฐ๊ณผ์ ๋ฃ๊ธฐ
result.add(Arrays.asList(nums[i], nums[left++], nums[right--]));
while (left < right && nums[left] == nums[left - 1]) ++left; // ์ซ์ ์ค๋ณต์ธ ์ผ์ด์ค ๋์ด๊ฐ๊ธฐ
}
}
}
}