国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

LeetCode 16. 3Sum Closest

2019-11-11 03:45:50
字體:
來源:轉載
供稿:網友

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

分析 先排序,然后左右夾逼,復雜度 O(n2)。

代碼

class Solution {public: int threeSumClosest(vector<int>& nums, int target) { int min_gap = INT_MAX; int result = 0; sort(nums.begin(), nums.end()); for (auto a = nums.begin(); a != PRev(nums.end(), 2); ++a) { auto b = next(a); auto c = prev(nums.end()); while (b < c) { int sum = *a + *b + *c; int gap = abs(sum - target); if (gap < min_gap) { min_gap = gap; result = sum; } if (sum < target) ++b; else --c; } } return result; }};
上一篇:凌亂的yyy

下一篇:三羊獻瑞

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 舞阳县| 正镶白旗| 万年县| 比如县| 通州区| 虹口区| 丹阳市| 双柏县| 四平市| 泗水县| 桃源县| 寿光市| 柳河县| 葵青区| 湘乡市| 长岭县| 昭平县| 五大连池市| 自治县| 马龙县| 上虞市| 灌阳县| 长治市| 内乡县| 安仁县| 旬阳县| 安平县| 吉首市| 九江市| 肥城市| 手机| 彭水| 乌鲁木齐市| 襄樊市| 石嘴山市| 剑阁县| 于田县| 内丘县| 常山县| 图们市| 乐陵市|