LeetCode:四数之和

题目:

给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 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]
]

我的答案:

思路参考三数之和

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if(nums==null||nums.length<4){
            return result;
        }
        Arrays.sort(nums);
        int L,R;
        for(int i=0;i<nums.length-3;i++){
            for(int j=i+1;j<nums.length-2;j++){
                L = j+1;
                R = nums.length-1;
                while(L<R){
                    int rs = nums[i]+nums[j]+nums[L]+nums[R]-target;
                    if(rs==0){
                        List<Integer> temp = new ArrayList<Integer>();
                        temp.add(nums[i]);
                        temp.add(nums[j]);
                        temp.add(nums[L]);
                        temp.add(nums[R]);
                        result.add(temp);
                        L++;
                        while(L<R&&nums[L]==nums[L-1]){
                            L++;
                        }
                        R--;
                    }else if(rs<0){
                        L++;
                        while(L<R&&nums[L]==nums[L-1]){
                            L++;
                        }
                    }else{
                        R--;
                    }
                }
                while(j+1<nums.length-2&&nums[j+1]==nums[j]){
                    j++;
                }
            }
            while(i+1<nums.length-3&&nums[i+1]==nums[i]){
                    i++;
            }
        }
        return result;
    }
}

官方题解:

没有官方题解

下面是一个优化解法

作者:you-wei-wu
链接:链接
来源:力扣(LeetCode)
 

总结:

这个优化方法其实在前面三数之和的时候看到了,就是先直接用最小/最大值来比较,就能节省一些时间

发布了75 篇原创文章 · 获赞 2 · 访问量 8024

猜你喜欢

转载自blog.csdn.net/wyplj2015/article/details/103411879