題目:
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.
nums給定一個長度為 的整數數組n和一個整數target,找出 中的三個整數,nums使得它們的和最接近target。
傳回三個整數的和。
您可以假設每個輸入只有一個解。
解題思路
這題和 15. 3Sum 很像,只是從「找到和為 0 的三元組」改成「找到最接近 target 的三元組和」。
排序 (Sorting)
先對陣列排序,方便使用雙指針。
固定一個數 + 雙指針
外層:固定一個數 nums[i]。
內層:雙指針 left = i+1, right = n-1。
計算總和 sum = nums[i] + nums[left] + nums[right]。
更新最接近的答案:如果 |sum - target| < |closest - target| → 更新。
移動指針
如果 sum < target,代表和太小 → left++。
如果 sum > target,代表和太大 → right--。
如果剛好相等 sum == target,直接回傳 target,因為不可能更接近。