-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3Sum.java
More file actions
33 lines (27 loc) · 1.08 KB
/
3Sum.java
File metadata and controls
33 lines (27 loc) · 1.08 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
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
int size = nums.length;
if(size < 3) return new ArrayList<>();
Arrays.sort(nums);
Set<List<Integer>> resultSet = new HashSet<>();
for(int i = 0; i < size - 2; i++) {
if(nums[i] > 0) break;
int begin = i+1;
int end = size-1;
do
{
while(begin < end - 1 && nums[i] + nums[begin] + nums[end] < 0) begin++;
while(begin < end - 1 && nums[i] + nums[begin] + nums[end] > 0) end--;
if(nums[i] + nums[begin] + nums[end] == 0) {
List<Integer> solution = new ArrayList<>(3);
solution.add(nums[i]);
solution.add(nums[begin]);
solution.add(nums[end]);
resultSet.add(solution);
}
begin++;
} while(begin < end);
}
return new ArrayList<>(resultSet);
}
}