leetcode 16. 最接近的三数之和

先排序,解决两数之和
之后从i开始,解决i以后的tar-nums[i]的两数的最近和

#include <bits/stdc++.h>

using namespace std;

#define debug(x) cout<<#x<<": "<<x<<endl;

class Solution {
public:
    int threeSumClosest(vector<int>& a, int tar) {

        sort(a.begin(),a.end());
        //debug(tar);
        int ret = INT_MAX;
        int ans = tar;
        for(int i=0;i < a.size()-2;i++){
            //debug(i)
            if ( abs(a[i] + two(a,i+1,tar-a[i]) - tar ) < ret ){
                ret = abs( a[i] + two(a,i+1,tar-a[i]) - tar );
                ans = a[i] + two(a,i+1,tar-a[i]);
            }
            if(ret == 0){
                cout<<a[i] + two(a,i+1,tar-a[i])<<endl;
                return a[i] + two(a,i+1,tar-a[i]);
                //return 0;
            }
        }
        return ans;
    }

    int two(vector<int> &a,int pos,int tar){
        int i = pos;
        //debug(pos);
        int cur_s = INT_MAX;
        int j = a.size()-1;
        int ret = 0;
        while(i < j){

            if( abs(a[i] + a[j] - tar) < cur_s){
                cur_s = abs(a[i] + a[j] - tar);
                ret = a[i] + a[j];
            }
            if(a[i] + a[j] < tar){
                i++;
            }else if(a[i] + a[j] > tar){
                j--;
            }else{
                return tar;

            }
            //debug(ret);
        }
        return ret;
    }

};



int main()
{
    vector<int> a = {1,1,1,1};
    Solution Solution1;
    debug( Solution1.threeSumClosest(a,0) );
    return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值