标签:
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:
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
标签:
原文地址:http://www.cnblogs.com/anne-vista/p/4886849.html