LeetCode演算法 4Sum 四數之和
阿新 • • 發佈:2018-12-11
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:
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]
]
解答
class Solution { public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> outList = new ArrayList<List<Integer>>(); int n = nums.length; if(n < 4) { return outList; } int t1,t2,sum,i,j,k,s; Arrays.sort(nums); t1 = nums[0]; for(i=0; i<n-3; i++){ if(i != 0 && t1 == nums[i]) continue; t2 = nums[i+1]; for(j = i+1; j<n-2; j++){ if(t2 == nums[j] && j>i+1) continue; sum = target - nums[i] -nums[j]; k = j+1; s = n-1; int t3,t4; while(k<s){ t3 = nums[k]; t4 = nums[s]; if(nums[k] + nums[s] == sum){ List<Integer> innerlist = new ArrayList<>(); innerlist.add(nums[i]); innerlist.add(nums[j]); innerlist.add(nums[k]); innerlist.add(nums[s]); outList.add(innerlist); k++; s--; while(t3 == nums[k] && k > j+1 && k<s) {k++;} while(t4 == nums[s] && s < n-1 && k<s) {s--;} }else if(nums[k] + nums[s] > sum){ s--; while(t4 == nums[s] && s < n-1 && k<s) {s--;} }else{ k++; while(t3 == nums[k] && k > j+1 && k<s) {k++;} } t2 = nums[j]; } t1 = nums[i]; } } return outList; } }