leetcode 4Sum题解

题目描述:

Given an array nums of n integers and an integer target, are there elements abc, 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]
]

中文理解:

给定一个数组和target,找出数组中左右和为target的四个数字组合,返回这些所有组合。

解题思路:

首先将数组排序,然后外层使用i,j双层循环,j>i,内层使用两个指针start,end,将题目转换为3sum来解决。

代码(java):

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> res=new ArrayList();
        if(nums.length<4)return res;
        Arrays.sort(nums);
        int flag=0;
        for(int i=0;i<nums.length-3;i++){
            if(i>0&&nums[i]==nums[i-1])continue;
            if(nums[i]==-1)System.out.println(nums[i]);
            for(int j=i+1;j<nums.length-2;j++){
                if(j>i+1 && nums[j]==nums[j-1])continue;
                if(nums[i]==-1)System.out.println(nums[i]+" "+nums[j]);
                int start=j+1,end=nums.length-1;
                while(start<end){
                    if(nums[i]==-1)System.out.println(nums[i]+" "+nums[j]+" "+nums[start]+" "+nums[end]);
                    int temp=nums[i]+nums[j]+nums[start]+nums[end];
                    if(temp<target){
                        start++;
                    }
                    else if(temp>target){
                        end--;
                    }
                    else if(temp==target){
                        res.add(Arrays.asList(nums[i],nums[j],nums[start],nums[end]));
                        while(start<end&&nums[start]==nums[start+1])start++;
                        while(start<end && nums[end]==nums[end-1])end--;
                        start++;
                        end--;
                    }
                }
            }
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/leo_weile/article/details/89948577