[LeetCode]16.3Sum Closest

本文介绍了一个算法问题,即在给定的整数数组中找到三个整数,使得它们的和最接近给定的目标值,并返回这个和。通过先排序数组,然后使用二分查找来逼近目标值,实现高效求解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【题目】

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).
【题意】

给定n个整数的数组S,寻找S中三个整数,使得总和最接近给定的目标。

返回三个整数的总和。

你可以假设每个输入将有一个确切的解决方案。

【分析】

题目思路和上题差不多。

先排序,二分查找来左右逼近。

对于a + b + c ,对a规定一个数值时,采用二分查找b,c使Sum= a + b + c 最接近target。

a可以取数组S中任何一个数值,使得有多个Sum,CurClosest = abs(target - Sum)求Min( CurClosest ),即最接近的那个。

【代码】

/*********************************
*   日期:2014-01-18
*   作者:SJF0115
*   题号: 16.3Sum Closest
*   来源:http://oj.leetcode.com/problems/3sum-closest/
*   结果:AC
*   来源:LeetCode
*   总结:
**********************************/
#include <iostream>
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <LIMITS.H>
using namespace std;

class Solution {
public:
    int threeSumClosest(vector<int> &num, int target) {
        int i,j,result,start,end,Sum,CurClosest,MinClosest = INT_MAX;
        int Len = num.size();
        //排序
        sort(num.begin(),num.end());
        for(i = 0;i < Len-2;i++){
            start = i + 1;
            end = Len - 1;
            //二分查找
            while(start < end){
                //a + b + c
                Sum = num[i] + num[start] + num[end];
                //接近度
                CurClosest = abs(target - Sum);
                //更新最接近的Target
                if(CurClosest < MinClosest){
                    MinClosest = CurClosest;
                    result = Sum;
                }
                //相等 -> 目标(唯一一个解)
                if(target == Sum){
                    return Sum;
                }
                //大于 -> 当前值小需要增大
                else if(target > Sum){
                    start ++;
                }
                //小于 -> 当前值大需要减小
                else{
                    end --;
                }
            }//while
        }//for
        return result;
    }
};
int main() {
    int result;
    Solution solution;
    vector<int> vec;
    vec.push_back(-1);
    vec.push_back(2);
    vec.push_back(1);
    vec.push_back(-4);
    result = solution.threeSumClosest(vec,-4);
    printf("Target:%d\n",result);
    return 0;
}







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@SmartSi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值