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:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- 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)
看到这道题似曾相识,想到了4sum的那个算法。于是就按照那个思路去实现了,然而太naive了,写了个时间复杂度为O(n3)的算法..O(n2)的晚上补充上。
先上O(n3)算法:
package leetcode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ThreeSum {
public static void main(String[] args) {
ThreeSum three = new ThreeSum();
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 9 };
int num03[] ={9,-4,-5,8,-5,7,5,-6,-4,-13,9,-10,-13,-6,2,-15,-13,-9,-4,-13,-9,-9,13,-13,-9,9,-15,1,0,-14,-8,-13,-11,-5,2,0,9,14,9,-9,8,-5,-12,10,-3,5,3,-1,12,14,1,10,12,-1,13,-12,-14,13,4,-7,6,4,-5,11,6,4,-12,0,3,4,-2,-3,7,1,14,-11,-8,2,-5,11,-7,3,6,-9,9,4,-14,10,-6,-2,-11,-14,-13,-9,4,0,11,-1,-15,-9,-12,-1,3,10,7,-5,6,6,12,8,2,-9,-4,-6,-11,-9,5,-10,-14,-15,3};
int nums02[] = {};
int target = 10;
List<List<Integer>> res = three.threeSum(num03, 0);
for (List<Integer> list : res) {
for (Integer integer : list) {
System.out.print(" " + integer);
}
System.out.println();
}
}
public List<List<Integer>> threeSum(int [] nums){
return threeSum(nums, 0);
}
public List<List<Integer>> threeSum(int[] nums, int target) {
Arrays.sort(nums);//还是要排序
// 固定两边,中间的一次循环
// int p1 = 0, p2 = nums.length - 1;
List<List<Integer>> res = new ArrayList<List<Integer>>();
for(int i=0;i<nums.length-3;i++){
for(int j=nums.length-1;j>=2;j--){
//中间的移动
int k = i+1;
while(k<j){
int tempres = nums[i]+nums[j]+nums[k];
if( tempres == target){
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(nums[i]);
temp.add(nums[k]);
temp.add(nums[j]);
if(!res.contains(temp))
res.add(temp);
}
k++;
}
}
}
return res;
}
}
觉得实现思路跟4sum是类似的,不过固定的是中间的那个数字,先给数组排序,从固定数字的左侧跟右侧扫,如果== target 左右侧各往中间靠近一位;如果小于target则小的一面,也就是左侧的指针向右移动一位;否则,右侧的指针向左移一位。