[LeetCode]3Sum Closest

news/2024/7/6 4:44:04

题目描述:(链接)

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

解题思路:

排序,左右夹逼!

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        int result = 0;
        if (nums.size() < 3) { return result; }
        
        int min = INT_MAX;
        sort(nums.begin(), nums.end());
        
        auto last = nums.end();
        for (auto i = nums.begin(); i != prev(last, 2); ++i) {
            auto j = i + 1;
            auto k = last - 1;
            
            while (j < k) {
                int sum = *i + *j + *k;
                int gap = abs(sum - target);
                if (gap < min) {
                    result = sum;
                    min = gap;
                }
                if (sum < target) { 
                    ++j ;
                } else {
                    --k;
                }
            }
        }
        
        return result;
    }
};

  

转载于:https://www.cnblogs.com/skycore/p/4853198.html


http://www.niftyadmin.cn/n/3433357.html

相关文章

recv()

说明我的想法之前&#xff0c;我先纠正一下上面我犯的几个错误&#xff0c;也许说明这些错误对楼主也有帮助。且听我慢慢道来&#xff0c;嘿嘿我的犯的最大错误是&#xff0c;没有搞清楚“模式”和“选项”&#xff0c;BLOCK是一种模式&#xff0c;而TIMEOUT只是一个在特定模式…

crontab-ui 管理 crontab

背景 以前在做定时任务的时候&#xff0c;都需要上网查一下怎么配置 crontab&#xff0c;因为这个东西不常用而且使用功能间隔可能会很长&#xff0c;每次需要用的时候可能都忘记上次是怎么用的&#xff0c;所以每次都需要去查怎么配置使用。这里介绍一个工具 crontab-ui 帮助…

python-序列对象方法(38)

>>> from random import randint >>> alist list() >>> list(hello) [h, e, l, l, o] >>> list((10,20,30)) #元组转换成列表 [10, 20, 30]>>> astr str() >>> str(10) #将数字转换成字符串 10 >>> str…

文件分片上传,断点续传

为什么文件要分片上传? 当单文件过大时&#xff0c;因为传输和后端处理文件时间过长都会导致时间过长&#xff0c;如果代理服务器没有在期望时间内获得后端处理程序返回内容&#xff0c;就会向前端抛出timeout错误。所以文件过大&#xff0c;需要对文件进行拆分&#xff0c;分…

ubuntu下SSH免密码登录设置

SSH服务器端&#xff1a;AA的SSH端口&#xff1a;portAA的用户名&#xff1a;nameAA的IP&#xff1a;IPA SSH访问端&#xff1a;BB的用户名&#xff1a;nameBB的IP&#xff1a;IPB效果&#xff1a;B通过SSH访问A1&#xff09;确认ssh是否安装&#xff08;通过重启来确认&#x…

纯 Git 实现前端 CI/CD

纯 Git 实现前端 CI/CD 原文链接:纯 Git 实现前端 CI/CD 最近要把前端 react 项目部署到私有服务器上,研究了好几种持续部署方案,这里简单描述一下。 总的部署思路分两种: 1.编译后的文件部署 编译后的文件部署,就是先在本地进行npm run build打包,生成 build 文件夹…

Winsock API 函数大全

Winsock API 函数大全 3 本系统(WinKing)提供之 Windows Sockets API 介面乃是依照 1993年1月20日公布之 WINSOCK 第1.1版(如附录)中所定义之函式 (routine)&#xff1b; 包括了30个Berkeley Software Distribution (BSD) 的函式以及16个符合 Windows Message-driven 特性的函…

python-字符串方法(40)

>>> py_str hello word! >>> py_str.capitalize() #把字符串的第一个字符大写 Hello word! >>> py_str.title() #每个单词的第一个字符大写 Hello Word! >>> py_str.center(50) #返回一个原字符串居中&#xff0c;并使用空格填充至长…