import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Solution { public List<List<Integer>> threeSum(int[] nums) { int size=nums.length; List<List<Integer>> res=new ArrayList<List<Integer>>(); if(size<3) return res; Arrays.sort(nums); size=nums.length; for(int i=0;i<size-2;i++) { int left=i+1; int right=size-1; while(left<right) { // System.out.println("left is :" + left); // System.out.println("right is :" + right); if(nums[i]+nums[left]+nums[right]==0) { //将结果加入到res当中 List<Integer> temp=new ArrayList<Integer>(); temp.add(nums[i]); temp.add(nums[left]); temp.add(nums[right]); res.add(temp); while(left<right&&nums[left+1]==nums[left]) left++; while(left<right&&nums[right-1]==nums[right]) right--; left++; right--; } else if(nums[i]+nums[left]+nums[right]>0) { right--; } else { left++; } } while(i+1<size&&nums[i+1]==nums[i]) i++; } return res; } }