Sum—LeetCode-18 4Sum

来源:互联网 发布:java中的同步 编辑:程序博客网 时间:2024/06/08 13:38

题目描述:

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]

]

思想:相对于3Sum来说,多加一层for循环,时间复杂度O(n*n*n),代码如下:

public List<List<Integer>> fourSum(int[] nums, int target) {        List<List<Integer>> resList = new ArrayList<List<Integer>>();        Arrays.sort(nums);        int pre = Integer.MAX_VALUE;        for(int i = 0;i < nums.length - 3; ++i){            int tempTarget = target - nums[i];            if(pre != nums[i]) {                List<List<Integer>> tempList = threeSum(nums, i+1, tempTarget);                if(null != tempList) {                    for(List<Integer> list: tempList){                        list.add(nums[i]);                        Collections.sort(list);                        resList.add(list);                    }                }            }            pre = nums[i];        }        return resList;    }    public List<List<Integer>> threeSum(int[] nums, int beginIndex, int target) {        List<List<Integer>> resList = new ArrayList<List<Integer>>();        int pre = Integer.MAX_VALUE;        for(int i = beginIndex;i < nums.length-2; ++i){            int tempTarget = target - nums[i];            if(pre != nums[i]){                List<List<Integer>> tempList = twoSum(nums, i+1, tempTarget);                if(null != tempList){                    for(List<Integer> list: tempList){                        list.add(nums[i]);                        resList.add(list);                    }                }            }            pre = nums[i];        }        return resList;    }    public List<List<Integer>> twoSum(int[] nums, int beginIndex, int target){        List<List<Integer>> resList = new ArrayList<List<Integer>>();        int end = nums.length - 1;        int preBeginElem = Integer.MAX_VALUE;        int preEndElem = Integer.MAX_VALUE;        while(beginIndex < end) {            if(nums[beginIndex] + nums[end] > target){                --end;            } else if(nums[beginIndex] + nums[end] < target){                ++beginIndex;            } else {                if(nums[beginIndex] != preBeginElem && nums[end] != preEndElem){                    List<Integer> tempList = new ArrayList<Integer>();                    tempList.add(nums[beginIndex]);                    tempList.add(nums[end]);                    resList.add(tempList);                }                preBeginElem = nums[beginIndex];                preEndElem = nums[end];                ++beginIndex;                --end;            }        }        return resList;    }


0 0
原创粉丝点击