博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] 3Sum Closest
阅读量:6853 次
发布时间:2019-06-26

本文共 1015 字,大约阅读时间需要 3 分钟。

This problem is very similar to 3Sum. You only need to maintain a variable for the sum that is closet to target. Also, some corner cases need to be handled; for example, nums does not have more than 2 elements.

The code is as follows, which is quite self-explanatory.

1     int threeSumClosest(vector
& nums, int target) { 2 sort(nums.begin(), nums.end()); 3 while (nums.size() <= 2) 4 return accumulate(nums.begin(), nums.end(), 0); 5 int ans = nums[0] + nums[1] + nums[2]; 6 for (int i = 0; i < nums.size() - 2; i++) { 7 int left = i + 1, right = nums.size() - 1; 8 while (left < right) { 9 int temp = nums[i] + nums[left] + nums[right];10 if (abs(temp - target) < abs(ans - target))11 ans = temp;12 if (temp == target) return ans;13 if (temp > target) right--;14 else left++;15 }16 }17 return ans;18 }

转载地址:http://mtfyl.baihongyu.com/

你可能感兴趣的文章
深入剖析某国外组织针对中国企业的APT攻击(CVE-2015-8651)
查看>>
Bandit Walkthrough
查看>>
一款开发中的中国风React组件库...
查看>>
CentOS 下使用 Pipenv + Gunicorn + Supervisor 部署 Flask 程序
查看>>
最新全国手机号码归属地信息SQLite数据库2019年2月更新
查看>>
Promise面试题,控制异步流程
查看>>
第一个springboot项目
查看>>
人工智能期末笔记
查看>>
如何正确地给图像添加高斯噪声
查看>>
HTML5 Geolocation API的正确使用
查看>>
从需求到数据到改进,如何形成闭环
查看>>
PM2自动部署代码流程总结
查看>>
[LeetCode] 432. All O`one Data Structure
查看>>
关于只触发自身绑定的事件
查看>>
前端进阶系列(三):HTML5新特性
查看>>
线性一致性和 Raft
查看>>
异步IO的应用
查看>>
Apache Ignite——新一代数据库缓存系统
查看>>
Laravel 5.8.2 发布,PHP 开发框架
查看>>
Django中的文件上传(利用class-based view)
查看>>