题解 | #三数之和#使用双指针思路后运行时间降到62ms
三数之和
https://www.nowcoder.com/practice/345e2ed5f81d4017bbb8cc6055b0b711
三层循环的方式,运行时间为205ms,使用了双指针思路降到62ms
import java.util.*; public class Solution { public ArrayList<ArrayList<Integer>> threeSum(int[] num) { ArrayList<ArrayList<Integer>> out = new ArrayList<>(); if (num.length < 3) { return out; } else { Arrays.sort(num);//先排序 for (int i = 0; i < num.length; i++) {//for循环逐个将数字作为三元组的第一个数字 int l = i + 1; int r = num.length - 1; while (r>l) {//当右侧指针下标大于左侧时,就一直循环 int sum = num[l] + num[r]; ArrayList<Integer> temp = new ArrayList<>(); temp.add(num[i]);//把三元组的第一个数字加入临时列表中 if (sum > 0 - num[i]) {//双指针对应的数字和大于所需值,需要减小,所以右侧那个左移 r--; } else if (sum < 0 - num[i]) {//双指针对应的数字和小于所需值,需要增大,所以左侧那个右移 l++; }else if(sum==0-num[i]){//双指针对应的数字和等于所需值 temp.add(num[l]); temp.add(num[r]); if(!out.contains(temp)){out.add(new ArrayList<>(temp));}//去重加入返回数组 l++;r--;//左右指针分别加减,保证下次循环从未遍历到的数字开始 } } } return out; } } }