Bernard Wong
  • Software Engineer
  • Problems
    • Lowest Common Ancestor of a Binary Tree
    • Longest Substring Without Repeating Characters
    • Longest Palindromic Substring
    • Longest Common Prefix
    • Isomorphic Strings
    • Integer to Roman
    • Frog Jump
    • Find the Difference
    • Find k closest elements to a given value
    • Longest Common Subsequence
    • Binary Search Tree from Sorted Array
    • Balanced Binary Tree
    • Sort Using Two Stacks
    • O(1) Stack
    • k-th element to last of a LinkedList
    • Dedup LinkedList
    • Check Rotated String
    • Compress String by Character Count
    • Escape HTML whitespace
    • Check String Permutation
    • Unique String
    • Container With Most Water
    • 4 Sum
    • 3 Sum Closest
    • 3 Sum
    • 2 Sum
    • Maximum Subarray
    • Nested List Weight Sum
    • Palindrome Number
    • Pow(x, n)
    • Regular Expression Matching
    • Remove Nth Node From End of List
    • Reverse Integer
    • Roman to Integer
    • Rotate Array
    • Search a 2D Matrix
    • Shortest Word Distance
    • Two Sum III - Data structure design
    • Valid Parentheses
    • ZigZag Conversion
    • Quicksort
    • Add Two Numbers
    • Best Time to Buy and Sell Stock
    • Letter Combinations of a Phone Number
  • Data Structures
    • Heap
Powered by GitBook
On this page
  1. Problems

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)

Previous4 SumNext3 Sum

Last updated 6 years ago