Created
January 21, 2016 05:01
-
-
Save jporcelli/34da9c41374f7daa9bd5 to your computer and use it in GitHub Desktop.
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
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
public class Solution { | |
public List<List<Integer>> threeSum(int[] nums) { | |
Arrays.sort(nums); | |
List<List<Integer>> R = new ArrayList<List<Integer>>(); | |
int N = nums.length; | |
for(int i=0; i<N; i++){ | |
int j=0, k=N-1; | |
while(j>=0 && j<i && k>i && k<N) { | |
int sum3 = nums[i]+nums[j]+nums[k]; | |
if(sum3 == 0) { | |
List<Integer> L = new ArrayList<>(3); | |
L.add(nums[j]); | |
L.add(nums[i]); | |
L.add(nums[k]); | |
R.add(L); | |
j++; k--; | |
} else if(sum3 > 0) k--; | |
else j++; | |
} | |
} | |
Set<List<Integer>> S = new HashSet<>(); | |
List<List<Integer>> T = new ArrayList<List<Integer>>(); | |
for(List<Integer> e : R){ | |
if(S.add(e)) T.add(e); | |
} | |
return T; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment