美文网首页LeetCode
16.最接近的三数之和

16.最接近的三数之和

作者: 闭门造折 | 来源:发表于2018-09-14 17:46 被阅读1次

给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。

例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

这道题比上一题简单,因为不需要剔重。
仍然使用双指针法,逐步向中间靠拢,维护一个dis,每次找到最小的差值绝对值
O(n^2)的方法

具体代码:

#include<vector>
#include<iostream>
#include<algorithm>

using namespace std;

int threeSumClosest(vector<int>& nums, int target) {
    int dis = INT_MAX;
    int res = 0;
    if(nums.size() < 3){
        return res;
    }
    
    sort(nums.begin(), nums.end());
    
    for(int i = 0; i < nums.size() - 2; i++){
        int tar = target - nums[i];
        int left = i + 1;
        int right = nums.size() - 1;
        while(left < right){
            if(nums[left] + nums[right] == tar){
                return target;
            }
            else if(nums[left] + nums[right] < tar){
                if(dis > tar - nums[left] - nums[right]){
                    dis = tar - nums[left] - nums[right];
                    res = target - dis;
                }
                left++;
            }
            else{
                if(dis > nums[left] + nums[right] - tar){
                    dis = nums[left] + nums[right] - tar;
                    res = target + dis;
                }
                right--;
            }
        }
    }
    
    return res;
}

int main(){
    int a[10] = {-1,2,1,-4};
    vector<int> nums(a, a+4);
    cout << threeSumClosest(nums, 1);
    return 0;
}

相关文章

  • LeetCode-16 最接近的三数之和

    题目:16. 最接近的三数之和 难度:中等 分类:数组 解决方案:双指针 今天我们学习第16题最接近的三数之和,这...

  • 力扣每日一题:16.最接近的三数之和 双指针解法

    16.最接近的三数之和 https://leetcode-cn.com/problems/3sum-closest...

  • 16.最接近的三数之和

    16.最接近的三数之和 题目链接:https://leetcode-cn.com/problems/3sum-cl...

  • 16. 三数之和最接近

    题目 给定一个整数数组 nums 和一个目标数 target,在 nums 中找出三个数,要求其和与 targe...

  • algrithrom

    求和问题,双指针解决 done 两数之和 三数之和 最接近三数之和 四数之和 链表反转问题 done 链表反转 链...

  • 16. 最接近的三数之和

    一、题目原型: 给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整...

  • 16.最接近的三数之和

    题目给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们...

  • 16. 最接近的三数之和

    知乎ID: 码蹄疾码蹄疾,毕业于哈尔滨工业大学。小米广告第三代广告引擎的设计者、开发者;负责小米应用商店、日历、开...

  • 16. 最接近的三数之和

    16.最接近的三数之和 给定一个包括n个整数的数组nums和 一个目标值target。找出nums中的三个整数,使...

  • 16.最接近的三数之和

    给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和...

网友评论

    本文标题:16.最接近的三数之和

    本文链接:https://www.haomeiwen.com/subject/ssxagftx.html