码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 4Sum

时间:2015-10-17 08:22:01      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:

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)

解题思路:

The core algorithm is similar as 3sum,  Leetcode 3Sum

using two pointers to approach from low and high. Just added two limit pointers[i, j], before two pointers[low, high].   Complexity: O(n^3)


Java code:

public class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        Arrays.sort(nums);
        for(int i = 0; i < nums.length; i++) {
            for(int j = i+1; j < nums.length; j++) {
                int low = j+1;
                int high = nums.length - 1;
                while(low < high){
                     int sum = nums[i] + nums[j]+nums[low] + nums[high];
                     
                     if(sum == target) {
                        result.add(Arrays.asList(nums[i], nums[j],nums[low], nums[high]));
                        while(i + 1 < nums.length && nums[i+1] == nums[i]) { 
                            i++;
                        }
                        while(j + 1 < nums.length && nums[j+1] == nums[j]) { 
                            j++;
                        }
                        while(low + 1 < nums.length && nums[low+1] == nums[low]) {
                            low++;
                        }
                        while(high -1 >= 0 && nums[high] == nums[high-1]) {
                            high--;
                        }
                        low++;
                        high--;
                     }else if(sum > target){
                         high--;
                     }else {
                         low++;
                     }
                }
            }
        }
        return result;
    }
}

Reference:

1. https://leetcode.com/discuss/61805/simple-82ms-two-pointers-java-solution

 

Leetcode 4Sum

标签:

原文地址:http://www.cnblogs.com/anne-vista/p/4886849.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!