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).<Solution>
這題是 3sum 的衍生題
基本想法都還是一樣,只是一些檢查條件不一樣
先排序,固定一個數,然後再去歷遍剩下兩個數的組合
這次不去記錄數組,而是和 target 的差距絕對值最小值
那因為題目有說只會有一組解,所以在一開始固定第一個數的時候
如果有重複,也不用再檢查了
code 如下
C++
Java
kotlin
沒有留言:
張貼留言