package 双指针; import java.util.*; public class 三数之和 { // 给定数组 nums = [-1, 0, 1, 2, -1, -4], // 满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ] static Map<Integer, ArrayList<Integer>> summap =new HashMap<>(); static int a =0; int arr [] ={1,0,-1,2,4,3,5,-2,-6,8}; for (int [] intlist:getsumthree(arr) ) { System.out.print("["); for (int i:intlist ) { System.out.print(i+","); } System.out.print("]"); } } static List<int[]> getsumthree(int [] arr){ List<int[]> paixv =new ArrayList<>(); Arrays.sort(arr); for (int i = 0; i < arr.length-1; i++) { if (arr[i]>0)return paixv; if (i>0&&arr[i-1] == arr[i] ){ continue; } int left =i+1; int right =arr.length-1; while (left<right){ int sum =arr[i]+arr[left]+arr[right]; if (sum>0){ right--; } else if (sum<0) { left++; }else { int[] temp = new int[]{arr[i], arr[left], arr[right]}; paixv.add(temp); while (right > left && arr[right] == arr[right - 1]) right--; while (right > left && arr[left] == arr[left + 1]) left++; right--; left++; } } } return paixv; } }
06-20
09-04