题解 | #三数之和#
三数之和
https://www.nowcoder.com/practice/345e2ed5f81d4017bbb8cc6055b0b711
运行时间:24ms超过95.60% 用Java提交的代码
import java.util.*;
public class Solution {
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
// 数组排序
Arrays.sort(num);
int len = num.length;
// 固定第一位数,剩下的两位数使用双指针
for(int i = 0; i < len - 2; i++){
int left = i + 1, right = len - 1;
// 去重
if(i > 0 && num[i] == num[i - 1]){
continue;
}
while(left < right){
if(num[i] + num[left] + num[right] == 0){
ArrayList<Integer> path = new ArrayList<>();
path.add(num[i]);
path.add(num[left]);
path.add(num[right]);
// 符合条件的数组添加到返回的列表中
res.add(path);
left++;
right--;
// 去重 注意使用while循环,重复的数组可能不止一个
while(left < right && num[left] == num[left - 1]){
left++;
}
// 去重
while(left < right && num[right] == num[right + 1]){
right--;
}
}else if(num[i] + num[left] + num[right] > 0){
right--;
// 去重
while(left < right && num[right] == num[right + 1]){
right--;
}
}else{
left++;
// 去重
while(left < right && num[left] == num[left - 1]){
left++;
}
}
}
}
return res;
}
}
查看14道真题和解析