LeetCode : 4Sum [java]

来源:互联网 发布:2016年最红的网络歌曲 编辑:程序博客网 时间:2024/04/30 08:15

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)

思路:确定前两个,双指针扫描后两个。

import java.util.Arrays;import java.util.List;import java.util.ArrayList;public class Solution {    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; i++) {while (i > 0 && i < nums.length && nums[i] == nums[i - 1]) {i++;}for (int j = i + 1; j < nums.length; j++) {while (j > i + 1 && j < nums.length && nums[j] == nums[j - 1]) {j++;}int left = j + 1;int right = nums.length - 1;while (left < right) {int sum = nums[i] + nums[j] + nums[left] + nums[right];if (sum > target) {while (right > left && nums[right] == nums[right - 1]) {right--;}right--;} else if (sum < target) {while (left < right && nums[left] == nums[left + 1]) {left++;}left++;} else {List<Integer> interList = new ArrayList<Integer>();interList.add(nums[i]);interList.add(nums[j]);interList.add(nums[left]);interList.add(nums[right]);list.add(interList);while (left < right && nums[left] == nums[left + 1]) {left++;}left++;}}}}return list;    }}


1 0
原创粉丝点击