leetcode— 3Sum

来源:互联网 发布:java调用通用短信接口 编辑:程序博客网 时间:2024/06/05 10:41

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]
]

class Solution {    public List<List<Integer>> threeSum(int[] nums) {        List<List<Integer>> res = new ArrayList<>();        if(nums==null || nums.length<3) return res;        Arrays.sort(nums);        for(int i=0; i<nums.length-2; i++){            if(i>0 && nums[i]==nums[i-1]) continue;            int left = i+1;            int right = nums.length-1;            int target = 0-nums[i];            while(left<right){                if(nums[left]+nums[right]==target){                    res.add(Arrays.asList(nums[i],nums[left],nums[right]));                    while(left<right && nums[left]==nums[left+1]) left++;                    while(left<right && nums[right]==nums[right-1]) right--;                    left++;                    right--;                }else if(nums[left]+nums[right]>target){                    right--;                }else{                    left++;                }            }        }        return res;    }}

**本题目的思路是先将数组排序,对于数组中的每一个元素,对[i+1,nums.length-1]应用two sum,只不过这里不能使用hashmap,要利用夹逼准则,解释一个问题,为什么是从[i+1,nums.length-1]中的i+1开始呢?而不是直接去掉第i个元素,然后在那些元素里面应用夹逼准则呢?
我们以选第一个和第二个举例,假设数组为A[],总共有n个元素A1,A2….An。很显然,当选出A1时,我们在子数组[A2~An]中求目标位target-A1的2sum问题,我们要证明的是当选出A2时,我们只需要在子数组[A3~An]中计算目标位target-A2的2sum问题,而不是在子数组[A1,A3~An]中,证明如下:
假设在子数组[A1,A3~An]目标位target-A2的2sum问题中,存在A1 + m = target-A2(m为A3~An中的某个数),即A2 + m = target-A1,这刚好是“对于子数组[A3~An],目标位target-A1的2sum问题”的一个解。即我们相当于对满足3sum的三个数A1+A2+m = target重复计算了。因此为了避免重复计算,在子数组[A1,A3~An]中,可以把A1去掉,再来计算目标是target-A2的2sum问题**

**其次就是写程序需要注意的地方
if(i>0 && nums[i]==nums[i-1]) continue;这一个语句使用i-1而不是i+1
因为i+1会导致跳过一部分值,
while(left