3 Sum Closest

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

For example, given array

S = {-1 2 1 -4}, and target = 1

The sum that is closest to the target is 2.

(-1 + 2 + 1 = 2)

def threeSumClosest(nums: Array[Int], target: Int): Int = {
  nums.length match {
    case l if l < 3 => throw new Error("not enough numbers")
    case l if l == 3 => nums.sum
    case _ => {
      scala.util.Sorting.quickSort(nums)
      var ret = Int.MaxValue
      for (i <- 0 until nums.length) {
        var j = i + 1
        var k = nums.length - 1
        while (j < k) {
          val current = nums(j) + nums(k) + nums(i)
          if (current == target) return target
          else if (math.abs(current - target) < math.abs(ret - target)) {
            ret = current
          }
          if (current > target) k -= 1
          if (current < target) j += 1
        }
      }
      ret
    }
  }
}

threeSumClosest(Array(1, 2, 3), 9)
threeSumClosest(Array(23, 3, 5, 1, 2), 9)

Last updated