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

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

LeetCode 16. 3Sum Closest

2019-11-11 05:43:23
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

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

分析 先排序,然后左右?jiàn)A逼,復(fù)雜度 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; }};
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 鹤岗市| 宁海县| 澎湖县| 商水县| 蓬莱市| 巴东县| 阿荣旗| 澎湖县| 武胜县| 博湖县| 获嘉县| 察雅县| 长丰县| 社旗县| 井冈山市| 遵义县| 铁岭市| 中卫市| 浦县| 政和县| 额济纳旗| 息烽县| 静海县| 辛集市| 万载县| 株洲市| 堆龙德庆县| SHOW| 维西| 嘉荫县| 阿城市| 乐亭县| 明溪县| 衡东县| 沈丘县| 静乐县| 丹巴县| 东乌珠穆沁旗| 汉源县| 哈巴河县| 习水县|