-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3sum leetcode
More file actions
29 lines (29 loc) · 1.04 KB
/
3sum leetcode
File metadata and controls
29 lines (29 loc) · 1.04 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
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List< List<Integer>> res=new ArrayList<>(); // Creating 2d List
Arrays.sort(nums); // sort the Array
for(int i=0;i<nums.length;i++){ // Iterate on Array
if(i>0 && nums[i]==nums[i-1]) // Skip Dublicate
continue;
int j=i+1; // Two pointer Approch (j And K)
int k=nums.length-1;
while(j<k){
int sum=nums[i]+nums[j]+nums[k]; // calculate the Total
if(sum>0)
k--;
if(sum<0)
j++;
if(sum==0){
res.add(Arrays.asList(nums[i], nums[j], nums[k])); // Add Array to List
j++;
k--;
while( j<k && nums[j]== nums[j-1]) // Skip the Dublicate Element
j++;
while( j<k && nums[k]==nums[k+1] ) // Skip the Dublicate Element
k--;
}
}
}
return res;
}
}