Created
July 17, 2021 11:25
-
-
Save ravitejamuddada/9e0a04b62ae82c25a827a3e17d9a3dd5 to your computer and use it in GitHub Desktop.
leetcode 3Sum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Input: nums = [-1,0,1,2,-1,-4] | |
Output: [[-1,-1,2],[-1,0,1]] | |
*/ | |
//if a+b+c=0 then output contains [a,b,c] | |
class Solution { | |
public List<List<Integer>> threeSum(int[] nums) { | |
//result that stores triplet | |
List<List<Integer>> result= new ArrayList<>(); | |
//sort the arry, so duplicates will be placed next to each other | |
Arrays.sort(nums); | |
int length=nums.length; | |
//iterate over the array till length-2 as we need 3 elements | |
for(int i=0;i<length-2;i++){ | |
//ignore if element is same as the prev element | |
if(i!=0 && nums[i]==nums[i-1]) continue; | |
//two pointers | |
int j=i+1; | |
int k=nums.length-1; | |
while(j<k){ | |
if(j!=i+1 && nums[j] == nums[j-1]){ | |
j++; | |
continue; | |
} | |
if(k!=length-1 && nums[k]==nums[k+1]){ | |
k--; | |
continue; | |
} | |
int sum=nums[i]+nums[j]+nums[k]; | |
if(sum==0){ | |
result.add(Arrays.asList(nums[i],nums[j++],nums[k])); | |
} | |
else if(sum<0){ | |
j++; | |
} | |
else{ | |
k--; | |
} | |
} | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment