-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15.3-sum.java
More file actions
82 lines (62 loc) · 1.92 KB
/
Copy path15.3-sum.java
File metadata and controls
82 lines (62 loc) · 1.92 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
82
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
// @lc code=start
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
// step 1: sort the array;
Arrays.sort(nums);
int n = nums.length;
for (int i = 0; i < n - 2; i++) {
// skip for first element;
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
/**
* a + b + c = 0;
* => b + c = -a;
*
* we fix first element , then we use 2 sum;
*/
int target = -nums[i];
int left = i + 1; // first
int right = n - 1; // last
while (left < right) {
int current_sum = nums[left] + nums[right];
if (current_sum == target) {
List<Integer> list = new ArrayList<>();
// frist element
list.add(nums[i]);
// second element
list.add(nums[left]);
// third element
list.add(nums[right]);
result.add(list);
// skip duplicates from left;
while (left < right && nums[left] == nums[left + 1]) {
left++;
}
// skip duplicates from right
while (left < right && nums[right] == nums[right - 1]) {
right--;
}
left++;
right--;
}
else if (current_sum < target) {
left++;
} else {
right--;
}
}
}
return result;
}
}
// @lc code=end
/*
* @lc app=leetcode id=15 lang=java
*
* [15] 3Sum
*/