Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums 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.
Example:
1 2 3 4 5 6 7 8
Given array nums = [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] ]
classSolution{ public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> res = new ArrayList<List<Integer>>(); if(nums == null || nums.length < 4) return res; Arrays.sort(nums); int len = nums.length;
for(int i = 0; i < len - 3; i++){ if(i != 0 && nums[i] == nums[i - 1]) continue; for(int j = i + 1; j < len - 2; j++){ if(j > i + 1 && nums[j] == nums[j - 1]) continue;
int left = j + 1; int right = len - 1; while(left < right){ int sum = nums[i] + nums[j] + nums[left] + nums[right]; if(sum > target) right--; elseif(sum < target) left++; else{ ArrayList<Integer> temp = new ArrayList<Integer>(); temp.add(nums[i]); temp.add(nums[j]); temp.add(nums[left]); temp.add(nums[right]); res.add(temp); left++; right--; while(left < right && nums[left] == nums[left - 1]) left++; while(left < right && nums[right] == nums[right + 1]) right--; } }
} }
return res; } }
454 4Sum II - Medium
Tags: Hash Map / Binary Search
Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.
To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13
Input: A = [ 1, 2] B = [-2,-1] C = [-1, 2] D = [ 0, 2]