标签:
题目描述:3Sum Closest
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).
分析:
和3Sum很像,设一个gap,每次都比较更新gap!
① gap == 0,则返回,因为题目说明只有一个解;
② gap > 0,q--;
③ gap < 0,p++;
④ 直到p == q。
代码如下:
class Solution { public: int threeSumClosest(vector<int> &num, int target) { int result = 0; int min_gap = INT_MAX; sort(num.begin(), num.end()); for(int i = 0; i < num.size(); i++){ int p = i + 1, q = num.size() - 1; while(p < q){ int sum = num[i] + num[p] + num[q]; int gap = abs(sum - target); if(gap < min_gap){ result = sum; min_gap = gap; } if(sum < target) p++; else q--; } } return result; } };
标签:
原文地址:http://www.cnblogs.com/510602159-Yano/p/4278876.html