3Sum

题目

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.

思路

前面我们介绍过如何从数组中找到和为target的两个数,该问题可以视为其拓展问题,可以利用相同的方法解决. 我们可以通过固定元素a,搜索和为-a的两个数

代码
public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        Arrays.sort(nums);

        for(int i=0; i<nums.length-2; i++){
            if(i==0 || (i>0 && nums[i]!=nums[i-1])){
                int target = -nums[i];
                int m = i+1, n = nums.length-1;
                while(m < n){
                    if(nums[m] + nums[n] < target)  m++;
                    else if(nums[m] + nums[n] > target) n--;
                    else{
                        List<Integer> comp = new ArrayList<Integer>();
                        comp.add(nums[i]);
                        comp.add(nums[m]);
                        comp.add(nums[n]);
                        result.add(comp);
                        while(m < n && nums[m]==nums[m+1]) m++;
                        while(m < n && nums[n]==nums[n-1]) n--;
                        m++;
                        n--;
                    }
                }
            }
        }
        return result;
    }
}
扩展

假如要寻找四个元素呢

public class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();

        Arrays.sort(nums);

        for(int i=0; i<nums.length-3; i++){
            if(i>0 && nums[i]==nums[i-1])   continue;
            for(int j=i+1; j<nums.length-2; j++){
                if(j>i+1 && nums[j]==nums[j-1])   continue;
                int l = j+1, r = nums.length-1;
                int sum = target - nums[i] - nums[j];

                while(l < r){
                    if(nums[l] + nums[r] > sum) r--;
                    else if(nums[l] + nums[r] < sum)    l++;
                    else{
                        result.add(Arrays.asList(nums[i],nums[j],nums[l],nums[r]));
                        while(l<r && nums[l]==nums[l+1])    l++;
                        while(l<r && nums[r]==nums[r-1])    r--;
                        l++;
                        r--;
                    }
                }
            }
        }
        return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值