Accepted Java solution


  • 0
    M
    public List<List<Integer>> fourSum(int[] nums, int target) {
        if(nums.length  <  4) return new ArrayList();
    	        List<List<Integer>> res = new ArrayList();
    	        Arrays.sort(nums);
    	        for(int i = 0; i < nums.length - 3; i++){
    	        	for(int j = nums.length - 1; j > i + 2; j--){
    	        		int start = i + 1, end = j - 1;
    	        		while(start < end){
    	        			int sum = nums[i] + nums[j] + nums[start] + nums[end];
    	        			if(sum == target){
    	        				List<Integer> arr = new ArrayList(Arrays.asList(nums[i], nums[start], nums[end], nums[j]));
    	        				if(!res.contains(arr))
    	        					res.add(arr);
    	        				end --;
    	        				start ++;
    	        			}else if(sum > target){
    	        				end --;
    	        			}else start ++;
    	        		}
    	        	}
    	        }
    	        return res;
    }

  • 0
    M

    And the 2-for can be add to n-for as nSum solution


Log in to reply
 

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