15. 3Sum

来源:互联网 发布:me042j a支持什么网络 编辑:程序博客网 时间:2024/06/16 10:57

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(nlogn)。
3Sum和核心是2Sum。如果是2Sum,只需两个变量j,k,分别从数组的左右两边开始循环,
(1)如果 num[j] + num[k] < 0,说明不等式左边的和太小了,此时应将 j 右移1位,即j++
(2)如果 num[j] + num[k] > 0,说明不等式左边的和太大了,此时应将 k 左移1位,即k–
这里写图片描述
在2Sum的基础上,外部再加一个从1到num.length-2的循环,作为第三个数可能出现的位置,构成3Sum。

public List<List<Integer>> threeSum(int[] nums) {        Arrays.sort(nums);        List<List<Integer>> result = new ArrayList<List<Integer>>();        for(int i = 0; i < nums.length - 2; i++) {            if(i > 0 && nums[i] == nums[i-1]) continue; // 避免产生重复的解            int j = i + 1;            int k = nums.length - 1;            while(j < k) {                int sum = nums[i] + nums[j] + nums[k];                if(sum == 0) {                    result.add(Arrays.asList(nums[i], nums[j], nums[k]));                    j++;                    k--;                    while(j < k && nums[j] == nums[j-1]) j++; // 避免产生重复的解                    while(j < k && nums[k] == nums[k+1]) k--; // 避免产生重复的解                }else if(sum < 0) {                    j++;                }else {                    k--;                }            }        }        return result;    }
原创粉丝点击