LeetCode 018 4Sum

4Sum

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

The solution set must not contain duplicate quadruplets.(不能重复元素)

在这里插入代码片Example:

Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

题目分析

和 015 的3sum很像,但是这里是四个元素,015 是第一个元素进行依次遍历,后面两个元素设定指针一前一后遍历。

这里则是前面两个元素做一次二重循环。后面两个元素设定指针一前一后遍历。

//代码是大神写的,非原创
class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
     List<List<Integer>> res = new ArrayList<>();
        if (nums == null || nums.length < 4) return res;
        Arrays.sort(nums);
        if (nums[0] + nums[1] + nums[2] + nums[3] > target ||
            nums[nums.length-1] + nums[nums.length-2] + nums[nums.length-3] + nums[nums.length-4] < target)
            return res;
        int len_3 = nums.length - 3;
        int len_2 = nums.length - 2;
        int len_1 = nums.length - 1;
        int last_i = nums[0] - 1;
        for (int i = 0; i < len_3; i++) {//第一个数,只能遍历到倒数第四个数
            if (nums[i] == last_i) continue;
            last_i = nums[i];
            int last_j = last_i - 1;
            for (int j = i + 1; j < len_2; j++) {//第二个数,只能遍历到倒数第三个数
                if (nums[j] == last_j) continue;
                last_j = nums[j];
                int innerTarget = target - last_i - last_j;
                if (nums[j+1] + nums[j+2] > innerTarget || nums[nums.length-1] + nums[nums.length-2] < innerTarget) continue;
                //后面就和 015 处理方式是一样的了
                int left = j + 1, right = len_1;
                while (left < right) {
                    int innerSum = nums[left] + nums[right];
                    if (innerSum == innerTarget) {
                        res.add(Arrays.asList(last_i, last_j, nums[left], nums[right]));
                        left++;
                        right--;
                        while (nums[left] == nums[left-1] && left < right) left++;
                        while (nums[right] == nums[right+1] && left < right) right--;
                    } else if (innerSum < innerTarget) {
                        left++;
                    } else {
                        right--;
                    }
                }
            }
        }

        return res;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值