首页 > 其他 > 详细

LeetCode 18 四数之和

时间:2020-10-27 23:08:14      阅读:22      评论:0      收藏:0      [点我收藏+]

LeetCode18 四数之和

题目描述

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

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

样例

给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。

满足要求的四元组集合为:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

算法分析

枚举两个变量,后两个变量,双指针算法

此题是LeetCode15题的变种,可以看下15题的思路

思路来源:小呆呆

时间复杂度\(O(n^{3})\)

Java代码

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

        for(int i = 0; i < n; i++){
            if(i!=0 && nums[i] == nums[i-1]) continue;
            for(int j = i+1; j<n; j++ ){
                if(j!=i+1 && nums[j] == nums[j-1]) continue;
                int l = j + 1;
                int r = n - 1;
                while(l < r){
                    int sum = nums[i] + nums[j] + nums[l] + nums[r];
                    if(sum > target){
                        r--;
                        continue;
                    }

                    if(sum < target){
                        l++;
                        continue;
                    }

                    ans.add(Arrays.asList(nums[i], nums[j],nums[l],nums[r]));

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

        return ans;
    }
}

LeetCode 18 四数之和

原文:https://www.cnblogs.com/vccyb/p/13887553.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!