JAVA--------------Easy Version To UnderStand!!!!!!


  • 2
    H
     public static List<List<Integer>> fourSum(int[] nums, int target) {
    	if(nums==null||nums.length==0)
    		return new ArrayList<List<Integer>>();
    	Arrays.sort(nums);
    	int len=nums.length;
    	List<List<Integer>> result=new ArrayList<List<Integer>>();
    	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 sum=target-nums[i]-nums[j],slow=j+1,fast=len-1;
    			while(slow<fast){
    				if(nums[slow]+nums[fast]==sum){
    					List<Integer> tmp=new ArrayList<Integer>();
    					tmp.add(nums[i]);
    					tmp.add(nums[j]);
    					tmp.add(nums[slow]);
    					tmp.add(nums[fast]);
    					result.add(tmp);
    					while(slow<fast&&nums[slow]==nums[slow+1])
    						slow++;
    					slow++;
    					while(fast>slow&&nums[fast]==nums[fast-1])
    						fast--;
    					fast--;
    				}
    				else if(nums[slow]+nums[fast]>sum)
    					fast--;   				
    				else
    					slow++;    					
    			}
    		}
    	}
        return result;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.