LeetCode|4Sum

来源:互联网 发布:shopnc java 源码 编辑:程序博客网 时间:2024/06/06 17:44

题目

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: 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]
]

总结:2Sum3Sum4SumKSum都是一类算法题,这里最主要的是优化时间复杂度,首先必须将给定的数组进行排序,然后确定K-2个数,剩下的两个数适用前后指针去遍历,得到的结果与目标数进行比较。

public class Solution {/** * 思路:首先需要对数组进行排序,使用两个for循环确定前两个数的值,然后使用前后指针去遍历除这两个数之外的数字,使这四个数相加 * 然后与目标数进行比较。 * 注意点:当遇到两个相同的数字的时候,需要做一些处理。 * 时间复杂度:o(n^3) */  public List<List<Integer>> fourSum(int[] nums, int target) {        if (nums == null) {            return null;        }        List<List<Integer>> result = new ArrayList<>();        Arrays.sort(nums);        for (int i = 0; i < nums.length; i++) {            if (i != 0 && nums[i - 1] == nums[i]) continue;            for (int j = i + 1; j < nums.length; j++) {                if (j !=i+1 && nums[j - 1] == nums[j]) continue;                int start = j + 1;                int end = nums.length - 1;                while (end > start) {                    int sum = nums[i] + nums[j] + nums[start] + nums[end];                    if (sum > target) {                        end--;                    } else if (sum < target) {                        start++;                    } else {                        result.add(Arrays.asList(nums[i], nums[j], nums[start], nums[end]));                        while (start + 1 < nums.length && nums[start + 1] == nums[start]) start++;                        while (end - 1 > 0 && nums[end - 1] == nums[end]) end--;                        start++;                        end--;                    }                }            }        }        return result;    }}
0 0
原创粉丝点击