[LeetCode-18]四数之和

题目链接:https://leetcode-cn.com/problems/4sum/


题目介绍:

给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。

注意:

答案中不可以包含重复的四元组。

示例:

在这里插入图片描述


解题思路:

  • 先对数组进行排序,然后两个for循环确定两个值后,通过左右指针确定后面两个数
  • 两个for循环在进行循环的时候需进行去重处理
  • 判断两个for循环和左右指针相加的值和target的大小进行判断,移动左右指针,从而确定目标值
  • 确定左右指针位置后,对左右指针分别进行判重处理
/**
 * @author: hyl
 * @date: 2019/08/03
 **/
public class Que18 {

    public List<List<Integer>> fourSum(int[] nums, int target) {

        List<List<Integer>> resultList = new ArrayList<List<Integer>>();

        if (nums.length < 4){
            return resultList;
        }

        Arrays.sort(nums);

        for (int i = 0; i < nums.length-2; i++) {

            //去重处理
            if (i > 0 && nums[i] == nums[i-1]){
                continue;
            }

            for (int j = i+1; j < nums.length-1; j++) {

                //去重处理
                if (j > i+1 && nums[j] == nums[j-1]){
                    continue;
                }

                //定义两个指针
                int l = j + 1;
                int r = nums.length-1;

                while (l < r){
                    int sum = nums[i] + nums[j] + nums[l] + nums[r];

                    //分别移动两个指针
                    if (sum < target){
                        l++;
                    }else if (sum > target){
                        r--;
                    }else{

                        List<Integer> list = new ArrayList<Integer>();

                        list.add(nums[i]);
                        list.add(nums[j]);
                        list.add(nums[l]);
                        list.add(nums[r]);

                        resultList.add(list);

                        //进行去重
                        while (l < r-1 && nums[l] == nums[l+1]){

                            l++;
                        }

                        while (r < nums.length-1 && nums[r] == nums[r+1]){
                            r--;
                        }

                        l++;
                        r--;
                    }
                }
            }
        }

        return resultList;
    }
}

总结:

  • 通过两个for循环个两个指针可以把复杂度提升到O(N^2 * logN)
  • 在进行for循环时需进行判重处理
  • 在得到确定的左右指针后需要进行判重处理

代码地址:

https://github.com/Han-YLun/LeetCode/blob/master/Practice/src/Que18.java


文章为阿伦原创,如果文章有错的地方欢迎指正,大家互相交流。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值