3Sum Closest

每日算法——leetcode系列


問題 3Sum Closest

Difficulty: Medium

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.

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

</pre>

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        
    }
};

翻譯

三數(shù)和

難度系數(shù):中等

給定一個有n個整數(shù)的數(shù)組S, 找出數(shù)組S中三個數(shù)的和最接近一個指定的數(shù)。 返回這三個數(shù)的和。 你可以假定每個輸入都有一個結(jié)果。

思路

思路跟3Sum很像, 不同的就是不用去重復(fù), 要記錄三和最接近target的和值。

代碼

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        int result = 0;
        int minDiff = INT32_MAX;
        // 排序
        sort(nums.begin(), nums.end());
        int n = static_cast<int>(nums.size());
        
        for (int i = 0; i < n - 2; ++i) {
          
            int j = i + 1;
            int k = n - 1;
            while (j < k) {
                int sum = nums[i] + nums[j] + nums[k];
                int diff = abs(sum - target);
                // 記錄三和最接近target的和值
                if (minDiff > diff){
                    result = sum;
                    minDiff = diff;
                }
                else if (sum < target){
                    j++;
                }
                else if (sum > target){
                    k--;
                }
                else{
                    return result;
                }
            }
        }
        return result;
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,775評論 0 33
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,932評論 0 23
  • 很多書告訴我們怎樣做加法,有些書卻可以告訴我們怎樣做減法,比如《別說你懂“英語啟蒙”》,還有最近翻看得《走進(jìn)孩子的...
    王小刀刀閱讀 235評論 1 1
  • 書生一直想跟所有人打好關(guān)系。 書生心想,似我這般自來熟的性子,跟誰都能聊得來,怎么可能不會因此而發(fā)展出友情呢?于是...
    喬梨ql閱讀 388評論 0 0
  • 自從新任武林盟主繼位,武林各派都再無紛爭,人人以禮相待,和諧共處。小生有幸曾一睹真容,現(xiàn)來為各位看官逐一介...
    李天諾閱讀 781評論 0 4