leetcode18.四数相加

https://leetcode-cn.com/problems/4sum/

双指针解法

思路和三数相加相同,就是把三数相加的第一个start变为temp = nums[i] + nums[j],(j > i),然后i和j都要做去重处理,避免出现相同元素,去重方法跟三数相加相同,避免出现-1,-1,-1,3作为开头被略过的情况。

上代码:

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

        for(int i = 0; i < nums.length - 1;i++){
            if(i > 0 && nums[i] == nums[i - 1]) continue;
            for(int j = i + 1; j < nums.length;j++){
                if(j > i + 1 && nums[j] == nums[j - 1]) continue;
                int temp = nums[i] + nums[j];
                int left = j + 1;
                int right = nums.length - 1;
                while(right > left){
                    int sum = temp + nums[left] + nums[right];
                    if(sum > target){
                        right--;
                    }else if(sum < target){
                        left++;
                    }else{
                        res.add(Arrays.asList(nums[i],nums[j],nums[left],nums[right]));
                        while(right > left && nums[right] == nums[right - 1]) right--;
                        while(right < left && nums[left] == nums[left + 1]) left++;

                        left++;
                        right--;
                    }
                }
            }
        }
        return res;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值