Lintcode59 3Sum Closest solution 題解

【題目描述】

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.

Notice:You may assume that each input would have exactly one solution.

給一個包含 n 個整數的數組 S, 找到和與給定整數 target 最接近的三元組,返回這三個數的和。

注意:只需要返回三元組之和,無需返回三元組本身

【題目鏈接】

www.lintcode.com/en/problem/3sum-closest/

【題目解析】

思路,類似於 3 Sum 問題,不同之處在於尋找與target的絕對值最小的數;同樣可以利用two pointers,對於 a + b + c 中的 b, c 來作爲兩個指針,a 爲 num[i], 那麼b初始值則爲 num[i + 1], c初始值爲num[len - 1]; 通過比較每次 a + b + c 的sum與target的大小,來確定移動b,或者移動c。

【參考答案】

www.jiuzhang.com/solutions/3sum-closest/


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章