class Solution {
public List<List<Integer>> threeSum(int[] num) {
List<List<Integer>> res = new LinkedList<>();//res存放结果
Arrays.sort(num);//将num排序
for(int i=0;i<num.length-2;i++){//遍历第一个数
if(num[i]>0) break;//最小的数都大于零,就没必要继续遍历了
if(i==0||num[i]!=num[i-1]){//skip the same result
//下面进行有序的2sum
int low =i+1,high=num.length-1;
while(low<high)
if(num[low]+num[high]==-num[i]) {
res.add(Arrays.asList(num[low],num[i],num[high]));
while(low<high&&num[low+1]==num[low])low++;//skip the same result
while(low<high&&num[high-1]==num[high])high--;//skip the same result
low++;
high--;
}else if(num[low]+num[high]<-num[i]) low++;
else high--;
}
}
return res;
}
}
LeetCode JAVA 15. 三数之和
最新推荐文章于 2024-05-20 18:16:07 发布