ez understanding JAVA solution


  • 0
    R
    public List<List<Integer>> fourSum (int[] nums, int target) {
     Arrays.sort(nums);
     List<List<Integer>> res = new LinkedList<>();
     for (int i = 0; i < nums.length - 3; i++) {
      for (int j = i + 1; j < nums.length - 2; j++) {
        int k = j + 1, l = nums.length - 1;
    	while ( k < l) {
    	  int sum = nums[i] + nums[j] + nums[k] + nums[l];
    	  if (sum == target) {
    	    res.add(Arrays.asList(nums[i], nums[j], nums[k], nums[l]));
    		while (k < l && nums[k] == nums[k + 1]) k++;
    		while (k < l && nums[l - 1] == nums[l]) l--;		
    			k++;
    			l--;
    	  }else if (sum > target)
    		l--;						
    	  else
    		k++;
    	  }
    	 while (j < nums.length - 2 && nums[j] == nums[j + 1]) j++;
    	}
       while (i < nums.length - 1 && nums[i] == nums[i + 1]) i++;
     }
     return res;
    }
    
    
    

Log in to reply
 

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