[牛客网-Leetcode] #数组 #哈希 #排序 中等 3sum-closet

最接近的三数之和 3sum-closet

题目描述

给出含有n个整数的数组s,找出s中和加起来的和最接近给定的目标值的三个整数。返回这三个整数的和。你可以假设每个输入都只有唯一解。
例如,给定的整数 S = {-1 2 1 -4}, 目标值 = 1.↵↵ 最接近目标值的和为 2. (-1 + 2 + 1 = 2).

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

示例

输入

[0,0,0],1

输出

0

解题思路

  • 先排序,用三指针
  • index指针用于遍历数组,初始为0,范围为0~n - 3(留出两个位置)
  • left和right指针用于每次index遍历时的双指针收缩,初始分别为index + 1和n - 1
  • temp = num[index] + num[left] + num[right]
    • 如果temp < target,则left ++
    • 如果temp >=target,则right - -
    • 如果abs(temp - target) < abs(res - target),则更新res
class Solution {
public:
    int threeSumClosest(vector<int>& num, int target) {
        int n = num.size();
        //先将原数组排序
        sort(num.begin(), num.end());
        //用于保存和目标值最接近的三数之和
        int res = num[0] + num[1] + num[n - 1];
        
        for(int index = 0; index < n - 2; index ++) {
            int left(index + 1), right(n - 1);
            while(left < right) {
                int temp = num[index] + num[left] + num[right];
                //如果三数之和小于目标值,就左指针加一,否则右指针减一
                temp < target ? left ++ : right --;
                //当三数之和与目标值相差最小时,更新res
                if(abs(temp - target) < abs(res - target)) {
                    res = temp;
                }
            }
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值