Note:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4},
A solution set is:
(-1, 0, 1)
(-1, -1, 2)
Idea: First sort the array. Then use three pointers (i,j,k) to denote the triplet (a,b,c). Fix i, use j,k to maintain a sliding window. If the current sum is 0, add to result; if the current sum <0, move the left pointer forward, if the current sum>0, move the right pointer backward. Skip the continuously same numbers to avoid duplication.
Time: O(n^2) Space: O(1)
Code:
public class Solution {
public List<List<Integer>> threeSum(int[] num) {
List<List<Integer>> result=new ArrayList<List<Integer>>();
if(num==null||num.length<3)
{
return result;
}
Arrays.sort(num);
for(int i=0;i<num.length-2;i++)
{
if(i>0&&num[i]==num[i-1])
continue;
int j=i+1;
int k=num.length-1;
while(j<k)
{
int curSum=num[i]+num[j]+num[k];
if(curSum<=0)
{
if(curSum==0)
result.add(Arrays.asList(num[i],num[j],num[k]));
j++;
while(j<k&&num[j]==num[j-1])
j++;
}
else
{
k--;
while(j<k&&num[k]==num[k+1])
k--;
}
}
}
return result;
}
}
No comments:
Post a Comment