LeetCode - Algorithms
  • Introduction
  • 1. Two Sum
  • 2. Add Two Numbers
  • 3. Longest Substring Without Repeating Characters
  • 4. Median of Two Sorted Arrays
  • 5. Longest Palindromic Substring
  • 6. ZigZag Conversion
  • 7. Reverse Integer
  • 8. String to Integer (atoi)
  • 9. Palindrome Number
  • 10. Regular Expression Matching
  • 11. Container with Most Water
  • 12. Integer to Roman
  • 13. Roman to Integer
  • 14. Longest Common Prefix
  • 15. 3Sum
  • 16. 3Sum Closest
  • 17. Letter Combinations of a Phone Number
  • 18. 4Sum
  • 19. Remove Nth Node From End of List
  • 20. Valid Parentheses
  • 21. Merge Two Sorted Lists
  • 22. Generate Parentheses
  • 23. Merge k Sorted Lists
  • 24. Swap Nodes in Pairs
  • 25. Reverse Nodes in k-Group
  • 26. Remove Duplicates from Sorted Array
  • 27. Remove Element
  • 28. Implement strStr()
  • 29. Divide Two Integers
  • 30. Substring with Concatenation of All Words
  • 31. Next Permutation
  • 32. Longest Valid Parentheses
  • 33. Search in Rotated Sorted Array
  • 34. Search for a Range
  • 35. Search Insert Position
  • 36. Valid Sudoku
  • 37. Sudoku Solver
  • 38. Count and Say
  • 39. Combination Sum
Powered by GitBook
On this page
  • Problem
  • Analysis
  • Code

16. 3Sum Closest

Problem

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).

Related Topics:

Array Two Pointers

Analysis

核心思想与 3Sum 相同。

这里需要注意:由于这题并不像 3Sum 能在过程中确定 a2 与 a3,所以不能像 3Sum 的解法一样跳过相邻的相同数。

Code

class Solution {

    fun threeSumClosest(nums: IntArray, target: Int): Int {

        nums.sort()

        var left: Int
        var right: Int
        var sub: Int
        var min = Int.MAX_VALUE

        loop@ for (i in 0 until nums.size - 2) {
            if (i == 0 || nums[i] != nums[i - 1]) {

                left = i + 1
                right = nums.size - 1

                while (left < right) {

                    sub = nums[left] + nums[right] + nums[i] - target
                    if (Math.abs(sub) < Math.abs(min)) {
                        min = sub
                    }

                    when {
                        sub == 0 -> break@loop
                        sub < 0 -> left++
                        else -> right--
                    }
                }
            }
        }

        return min + target
    }
}
Previous15. 3SumNext17. Letter Combinations of a Phone Number

Last updated 6 years ago