-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3sum.java
48 lines (39 loc) · 1.3 KB
/
3sum.java
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
// Problem link - https://leetcode.com/problems/3sum/description/
// TC - O(n * n)
// SC - O(nlogn) - (sorting)
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
int n = nums.length;
List<List<Integer>> triplets = new ArrayList<>();
Arrays.sort(nums);
for(int i = 0; i < n; i++){
//skipping duplicates
if(i > 0 && nums[i] == nums[i - 1]) continue;
int target = -nums[i];
int j = i + 1, k = n - 1;
while(j < k){
if(nums[j] + nums[k] == target){
if(j > i + 1 && nums[j] == nums[j - 1]){
j++;
continue;
}
if(k < n - 1 && nums[k] == nums[k + 1]){
k--;
continue;
}
List<Integer> triplet = new ArrayList<>();
triplet.add(nums[i]);
triplet.add(nums[j]);
triplet.add(nums[k]);
triplets.add(triplet);
j++;
} else if(nums[j] + nums[k] < target){
j++;
} else {
k--;
}
}
}
return triplets;
}
}