meta data for this page
  •  

3Sum Closest

Leetcode


Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target.

Return the sum of the three integers.

You may assume that each input would have exactly one solution.

Example 1:

Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Solution 1

Solution 1

public int threeSumClosest(int[] nums, int target) {
  if (nums.length < 3) {
    return 0;
  }
 
  if (nums.length == 3) {
    return nums[0] + nums[1] + nums[2];
  }
 
  Arrays.sort(nums);
  Integer bestMatch = null;
  for (int i = 0; i < nums.length - 2; i++) {
    for (int j = i + 1; j < nums.length - 1; j++) {
      for (int k = j + 1; k < nums.length; k++) {
        if (bestMatch == null) {
          bestMatch = nums[i] + nums[j] + nums[k];
        }
        int sum = nums[i] + nums[j] + nums[k];
        bestMatch = (Math.abs(target-sum) < Math.abs(target-bestMatch)) ? sum : bestMatch;
      }
    }
  }
  return bestMatch;
}