首页 > 代码库 > Array-4Sum问题

Array-4Sum问题

LeetCode第18题--4Sum

Given an array S of n integers, are there elements a, b, c, and d in S 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.

For example, given array S = [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]
]
 1 //解题思路:将之前解决的3Sum问题再加一层循环,注意两层for循环中的条件
 2 public class Solution {
 3     public List<List<Integer>> fourSum(int[] nums, int target) {
 4        List<List<Integer>> result = new LinkedList<>();
 5        if(nums == null || nums.length < 4) {
 6            return result;
 7        }
 8        Arrays.sort(nums);//注意一般情况都是要先进行排序的
 9        for(int first = 0; first < nums.length - 3; first++) {
10            if(first > 0 && nums[first] == nums[first - 1]) {
11                continue;
12            }
13            for(int second = first + 1; second < nums.length - 2; second++) {
14                if(second > first + 1 && nums[second] == nums[second - 1]) {//这里要注意的是 second > first + 1
15                    continue;
16                }
17                int left = second + 1; int right = nums.length - 1; int target1 = target - (nums[first] + nums[second]);
18                while(left < right) {
19                    int sum = nums[left] + nums[right];
20                    if(sum == target1) {
21                        result.add(Arrays.asList(nums[first], nums[second], nums[left], nums[right]));
22                        while(left < right && nums[left] == nums[left + 1]) left++;
23                        while(left < right && nums[right] == nums[right - 1]) right--;
24                        left++;
25                        right--;
26                    } else if(sum < target1) {
27                        left++;
28                    } else {
29                        right--;
30                    }
31                }
32            }
33        }
34        return result;
35     }
36 }

 

Array-4Sum问题