Created
October 4, 2014 19:08
-
-
Save sreeprasad/c99615cc4b2a576d1989 to your computer and use it in GitHub Desktop.
ThreeSum
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 static List<List<Integer>> trip(int[] num) { | |
List<List<Integer>> result = new ArrayList<List<Integer>> (); | |
ArrayList<Integer> sol = new ArrayList<Integer>(); | |
if(num.length==0 || num.length<3){ | |
return result; | |
} | |
Arrays.sort(num); | |
for(int i=0;i<num.length;i++){ | |
int target = 0-num[i]; | |
int st = i+1; | |
int end = num.length-1; | |
while(st<end){ | |
if(num[st]+num[end]==target){ | |
sol.add(num[i]); | |
sol.add(num[st]); | |
sol.add(num[end]); | |
st++; | |
end--; | |
while( (st<end) && num[st]==num[st-1]) st++; | |
while( (st<end) && num[end]==num[end+1]) end--; | |
result.add(sol); | |
sol = new ArrayList<Integer>(); | |
}else if(num[st]+num[end]<target){ | |
st++; | |
}else{ | |
end--; | |
} | |
if(i<num.length-1) | |
while(i+1<num.length-1 && num[i]==num[i+1]) i++; | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment