-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution_15.java
More file actions
54 lines (51 loc) · 1.73 KB
/
Solution_15.java
File metadata and controls
54 lines (51 loc) · 1.73 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
/*15. 三数之和
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
*/
import java.util.*;
class Solution {
public static void main ( String[] args ) {
int[] nums = {-1, 0, 1, 2, -1, -4};
List<List<Integer>> ans = threeSum(nums);
int l = ans.size();
for (int i = 0 ; i < l ; i++ )
System.out.println(ans.get(i).toString());
}
public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
Arrays.sort(nums);
for (int i = 0 ; i < nums.length - 2 ; i++ ) {
if ( nums[i] > 0 )
break;
if ( i != 0 && nums[i] == nums[i - 1] )
continue;
int L = i + 1 ;
int R = nums.length - 1;
while ( L < R ) {
int sum = nums[i] + nums[L] + nums[R];
if ( sum == 0 ) {
List<Integer> tmp = new ArrayList<>();
tmp.add(nums[i]);
tmp.add(nums[L]);
tmp.add(nums[R]);
ans.add(tmp);
while ( L < R && nums[L] == nums[L + 1] )
L++;
while ( L < R && nums[R] == nums[R - 1] )
R--;
L++;
R--;
} else if ( sum > 0 )
R--;
else L++;
}
}
return ans;
}
}