3 Sum Closest
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