Skip to content

Instantly share code, notes, and snippets.

@guolinaileen
Last active December 11, 2015 18:59
Show Gist options
  • Save guolinaileen/4645807 to your computer and use it in GitHub Desktop.
Save guolinaileen/4645807 to your computer and use it in GitHub Desktop.
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector< int > > result;
if(num.size()<3) return result;
sort(num.begin(), num.end());
for(int i=0; i<=num.size()-3; i++)
{
int first=num[i];
if(i!=0 && num[i]==num[i-1]) continue;
int j=i+1, k=num.size()-1;
while(j<k)
{
int temp=num[j]+num[k];
if(temp==-first)
{
vector<int> tempResult;
tempResult.push_back(first);
tempResult.push_back(num[j]);
tempResult.push_back(num[k]);
result.push_back(tempResult);
j++;
k--;
}else if(temp<-first)
{
j++;
}else
{
k--;
}
while(j-1!=i && num[j]==num[j-1])
{
j++;
}
while(k+1!=num.size() && num[k]==num[k+1])
{
k--;
}
}
}
return result;
}
};
public class Solution {
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
int length=num.length;
ArrayList<ArrayList<Integer>> result= new ArrayList<ArrayList<Integer>>();
if(length<3) return result;
Arrays.sort(num);
for(int i=0; i<length; i++)
{
if(i!=0 && num[i]==num[i-1]) continue;
int target=-1*num[i];
int start=i+1;
int end=length-1;
while(start<end)
{
int temp=num[start]+num[end];
if(temp==target)
{
ArrayList<Integer> subResult=new ArrayList<Integer>();
subResult.add(num[i]);
subResult.add(num[start]);
subResult.add(num[end]);
result.add(subResult);
start++;
end--;
while(start<end && num[start]==num[start-1])
{
start++;
}
while(end>start && num[end]==num[end+1])
{
end--;
}
}else if(temp<target)
{
start++;
}else
{
end--;
}
}
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment