-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
46 lines (41 loc) · 1.29 KB
/
Copy pathMain.java
File metadata and controls
46 lines (41 loc) · 1.29 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
// LeetCode Problem: https://leetcode.com/problems/3sum/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
Arrays.sort(nums);
for(int i=0; i<nums.length; i++){
if(i > 0 && nums[i] == nums[i-1])
continue;
int j = i+1;
int k = nums.length - 1;
while(j < k){
long sum = nums[i] + nums[j] + nums[k];
if(sum == 0){
ans.add(Arrays.asList(nums[i], nums[j], nums[k]));
j++;
k--;
while(j < k && nums[k] == nums[k+1])
k--;
while(j < k && nums[j] == nums[j-1])
j++;
} else if (sum > 0){
k--;
} else {
j++;
}
}
}
return ans;
}
}
public class Main {
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums = {-1, 0, 1, 2, -1, -4};
List<List<Integer>> result = solution.threeSum(nums);
System.out.println(result);
}
}