Middle-题目100: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:
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.
题目大意:
给出一个数组和目标值target,找出4个数使得和值为target,求出所有解。
题目分析:
既然不要求保持顺序,那么用ksum的通法,先排序再固定k-2个指针即可
源码:(language:java)

public class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        Arrays.sort(nums);
        for(int i = 0;i<nums.length-3;i++) {
            for(int j = nums.length-1;j-i>=3;j--) {
                int sum1 = nums[i]+nums[j];
                int m1 = i+1,m2 = j-1;
                while(m1<m2) {
                    int sum = sum1+nums[m1]+nums[m2];
                    if(sum == target) {
                        List<Integer> sublist = new ArrayList<Integer>();
                        sublist.add(nums[i]);
                        sublist.add(nums[m1]);
                        sublist.add(nums[m2]);
                        sublist.add(nums[j]);
                        if(!list.contains(sublist))
                            list.add(sublist);
                        m1++;
                    }
                    else if(sum > target)
                        m2--;
                    else // sum < target
                        m1++;
                }
            }
        }
        return list;
    }
}  

成绩:
56ms,beats 59.49%,众数57ms,4.51%
Cmershen的碎碎念:
本题的去重处理没有做,而是直接遍历list来排除重复解的,否则还能更快一些。

你可能感兴趣的:(Middle-题目100:18. 4Sum)