leetcode 18. 4Sum——better way

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

//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:
//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)




public class Solution {
	
	public static void main(String[] args) {
		int[] a = {-1,2,2,-5,0,-1,4};
		List<List<Integer>> result = fourSum(a,3);
		for(int i = 0;i<result.size();i++){
			System.out.println(result.get(i));
		}
	}
	
	public static List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        HashSet<List<Integer>> contrast = new HashSet<List<Integer>>();								
        Arrays.sort(nums);
        for(int i = 0;i<nums.length;i++){										//与3sum相似,先确定第一个元素
        	for(int j = i+1;j<nums.length;j++){									//确定第二个元素
        		int k = j+1;													//后两个元素取之后总体元素的两端
        		int l = nums.length-1;
        		while(k<l){														
            		int sum = nums[i]+nums[j]+nums[k]+nums[l];
        			if(sum>target){												//根据sum与target的比较确定l和k如何移动
            			l--;
            		}else if(sum<target){
            			k++;
            		}else if(sum == target){
            			List<Integer> temp = new ArrayList<Integer>();
            			temp.add(nums[i]);
            			temp.add(nums[j]);
            			temp.add(nums[k]);
            			temp.add(nums[l]);
            			if(!contrast.contains(temp)){								//查看result中是否存在
            				contrast.add(temp);
            				result.add(temp);
            			}
            			k++;
            			l--;
            		}
        		}
        	}
        }
        return result;
    }
	
}

		

你可能感兴趣的:(java,LeetCode)