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) {
        
    }
};

翻译

三数和

难度系数:中等

给定一个有n个整数的数组S, 找出数组S中三个数的和最接近一个指定的数。 返回这三个数的和。 你可以假定每个输入都有一个结果。

思路

思路跟3Sum很像, 不同的就是不用去重复, 要记录三和最接近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;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,766评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,793评论 0 23
  • 很多书告诉我们怎样做加法,有些书却可以告诉我们怎样做减法,比如《别说你懂“英语启蒙”》,还有最近翻看得《走进孩子的...
    王小刀刀阅读 235评论 1 1
  • 书生一直想跟所有人打好关系。 书生心想,似我这般自来熟的性子,跟谁都能聊得来,怎么可能不会因此而发展出友情呢?于是...
    乔梨ql阅读 387评论 0 0
  • 自从新任武林盟主继位,武林各派都再无纷争,人人以礼相待,和谐共处。小生有幸曾一睹真容,现来为各位看官逐一介...
    李天诺阅读 772评论 0 4