【leetcode】【18】4Sum

来源:互联网 发布:119手游网 92kaifa源码 编辑:程序博客网 时间:2024/06/06 12:31

一、问题描述

Given an array S of n integers, are there elements abc, 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:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
  • 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)

二、问题分析

此题与3Sum也是类似的,只不过需要多套一层循环。

三、Java AC代码

public List<List<Integer>> fourSum(int[] nums, int target) {List<List<Integer>> list = new ArrayList<List<Integer>>();if (nums == null || nums.length < 4) {return list;}Arrays.sort(nums);for (int i = 0; i < nums.length - 3; i++) {if (i == 0 || nums[i] != nums[i - 1]) { // remove duplicatefor (int j = i + 1; j < nums.length - 2; j++) {if (j == i + 1 || nums[j] != nums[j - 1]) {int start = j + 1;int end = nums.length - 1;while (start < end) {int sum = nums[i] + nums[j] + nums[start] + nums[end];if (sum == target) {list.add(Arrays.asList(nums[i], nums[j], nums[start], nums[end]));while (start < end&& nums[start++] == nums[start]);while (start < end && nums[end--] == nums[end]);} else if (sum > target) {end--;} else {start++;}}}}}}return list;}


0 0
原创粉丝点击