18. 4Sum

来源:互联网 发布:js获取身份证号码 编辑:程序博客网 时间:2024/06/04 08:03

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]]
  • 题目大意:给定一个包含n个数的数组S,一个target,寻找数组中4个和为target的所有数列。

  • 思路:根据3sum进行扩充。

  • 代码:

    package Array;import java.util.ArrayList;import java.util.Arrays;import java.util.List;/*** @Author OovEver* @Date 2017/11/28 10:10*/public 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);      for (int i = 0; i < nums.length - 3; i++) {//            最前面四个数大于target,则不用判断,直接跳出循环          if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) {              break;          }//            第一个数和最后三个数和小于target,则在此区间,不可能有等于target得数,continue          if (nums[i] + nums[nums.length - 1] + nums[nums.length - 2] + nums[nums.length - 3] < target) {              continue;          }//            跳过重复的数          if (i > 0 && nums[i] == nums[i - 1]) {              continue;          }//            同上          for(int j=i+1;j<nums.length-2;j++) {              if (nums[j] + nums[j + 1] + nums[j + 2] > target - nums[i]) {                  break;              }//                同上              if (nums[j] + nums[nums.length - 1] + nums[nums.length - 2] < target - nums[i]) {                  continue;              }              if (j > i + 1 && nums[j] == nums[j - 1]) {                  continue;              }              int low = j + 1;              int high = nums.length - 1;              while (low < high) {                  int sum = nums[i] + nums[j] + nums[low] + nums[high];                  if (sum == target) {                      res.add(Arrays.asList(nums[i], nums[j], nums[low], nums[high]));                      while (low<high&&nums[low]==nums[low+1]) low++;                      while (low<high&&nums[high]==nums[high-1]) high--;                      low++;                      high--;                  } else if (sum < target) {                      low++;                  } else {                      high--;                  }              }          }      }      return res;  }}

原创粉丝点击