问题描述:
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
解题思想:固定一个值,就可以转化为两个数和等于指定值,要学会抽象思维,时间复杂度O(n*n),见代码:
public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> resList = new ArrayList<List<Integer>>(); Arrays.sort(nums); int pre = Integer.MAX_VALUE; for(int i = 0;i < nums.length-2; ++i){ int target = nums[i] * (-1); if(pre != nums[i]){ List<List<Integer>> tempList = twoSum(nums, i+1, target); if(null != tempList){ for(List<Integer> list: tempList){ List<Integer> temp = new ArrayList<Integer>(); temp.add(nums[i]); temp.add(list.get(0)); temp.add(list.get(1)); resList.add(temp); } } } pre = nums[i]; } return resList; } public List<List<Integer>> twoSum(int[] nums, int beginIndex, int target){ List<List<Integer>> resList = new ArrayList<List<Integer>>(); int end = nums.length - 1; int preBeginElem = Integer.MAX_VALUE; int preEndElem = Integer.MAX_VALUE; while(beginIndex < end) { if(nums[beginIndex] + nums[end] > target){ --end; } else if(nums[beginIndex] + nums[end] < target){ ++beginIndex; } else { if(nums[beginIndex] != preBeginElem && nums[end] != preEndElem){ List<Integer> tempList = new ArrayList<Integer>(); tempList.add(nums[beginIndex]); tempList.add(nums[end]); resList.add(tempList); } preBeginElem = nums[beginIndex]; preEndElem = nums[end]; ++beginIndex; --end; } } return resList; }