3 Sum Closet

題目

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.

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

https://leetcode.com/problems/3sum-closest/description/

樣例

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

例如 S = [-1, 2, 1, -4] and target = 1. 和最接近 1 的三元組是 -1 + 2 + 1 = 2.

解題思路

這道題的仍然是使用兩個指針 Two Pointers的方法來解決,解題思路和3 Sum這道題相似,這里的時間復雜度仍然是O(n^2)。

分別使用3個指針來指向當前元素、下一個元素和最后一個元素。如果結果Sum是小于目標值的,我們就將下一個元素接著向數組右側遍歷;如果結果Sum是大于目標值的,那么我們將最后一個元素向左側遍歷。
并且,每次我們都比較當前結果和目標值的差值,如果這個差值小于上一次的結果,將上一次的結果替換,否則的話,繼續遍歷。

具體代碼如下:

public int threeSumClosest(int[] nums, int target) {
        int res = nums[0] + nums[1] + nums[nums.length - 1];
        Arrays.sort(nums);
        
        for (int i = 0; i < nums.length; i++) {
            int left = i + 1;
            int right = nums.length - 1;
            
            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (sum == target) {
                    res = sum;
                    return res;
                } else if (sum < target) {
                    left++;
                } else {
                    right--;
                }
                if (Math.abs(sum - target) < Math.abs(res - target)) {
                     res = sum;
                }
            }
        }
        return res;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,775評論 0 33
  • Two Sum 題目: Given an array of integers, find two numbers ...
    lyoungzzz閱讀 406評論 0 0
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,932評論 0 23
  • 到這里,在ZEALANDIA的時間就還剩下這兩周了,五點上班的悲催生活隨著先我們前一周入職的小伙伴的即將離開也快要...
    cora的生活手冊閱讀 414評論 0 1
  • 不知道是不是所有十七八歲的孩子們都像我一樣,明明應該是積極向上但大多數時間都是處于迷茫慌張的狀態。 十七八歲的...
    嘩啦啦嚕閱讀 119評論 0 0