leetcode 16. 3Sum Closest

題目描述

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

思路

目的:找到三個(gè)數(shù)的和最接近target。

排序,從小到大,使與target之差值越來(lái)越小。i,j最小,k最大,然后去找合適值。

  1. 如果三個(gè)數(shù)之和大于target,判斷之差是否比目前最小差更小,更小就更新結(jié)果以及最小差,同時(shí)將j增大。
  2. 反之同理。
  3. 相等就是了。

代碼

class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
    if (nums.size() < 3)
    {
        return -1;
    }
    int res = 0;//最后答案
    int distance = INT_MAX;//總的最近的差,包括大的和小的
    int i, j, k;
    sort(nums.begin(),nums.end());//先排序
    for (i = 0; i < nums.size() - 2; i++)
    {
        j = i + 1;
        k = nums.size() - 1;
        while (j < k)
        {
            int temp = nums[i] + nums[j] + nums[k];
            int temp_distance;
            if (temp < target)//說(shuō)明太小了,要變大
            {
                temp_distance = target - temp;//當(dāng)前三個(gè)值與target的差
                if (temp_distance < distance)//更接近了可以進(jìn)行更新
                {
                    res = temp;
                }
                j++;
            }
            else if(temp > target)
            {
                    temp = nums[i] + nums[j] +     nums[k];
                    temp_distance = temp - target;
                if (temp_distance < distance)
                {
                res = temp;
                }
                k--;
            }
            else
            {
                temp = nums[i] + nums[j] + nums[k];
                res = temp;
            }
        }
    }
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容