LeetCode算法 4Sum 四数之和

Given an array nums of n integers and an integer target, are there elements abc, 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> fourSum(int[] nums, int target) {
        List> outList = new ArrayList>();
        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; ii+1) continue;
	        	sum = target - nums[i] -nums[j];
	        	k = j+1;
	        	s = n-1;
                int t3,t4;
	        	while(k 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 sum){
	        			s--;
                        while(t4 == nums[s] && s < n-1 && k j+1 && k

 

你可能感兴趣的:(LeetCode算法 4Sum 四数之和)