首页 > 代码库 > [leetcode]3 Sum closest
[leetcode]3 Sum closest
问题描述:
Given an array S of n integers, find three integers inS 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).
基本思路:
本题可以利用上一篇《3 Sum》相同的思路来处理。就是对数组排序,然后利用数字之间的序关系减少对不必要情况的处理。
代码:
int threeSumClosest(vector<int> &num, int target) //C++ { //You may assume that each input would have exactly one solution. int sum = num[0]+num[1]+num[2]; int dif = abs(sum -target); sort(num.begin(), num.end()); for (int i = 0; i < num.size() - 2;) { int l = i + 1, r = num.size() - 1; while (l < r) { int tmpdif = num[l] + num[r] + num[i] - target; if ( tmpdif <= -dif) l++; else if (tmpdif > -dif && tmpdif < dif) { dif = abs(tmpdif); sum = num[l] + num[r] + num[i]; if(tmpdif < 0) do { l++; }while (l < r && num[l - 1] == num[l]); else if(tmpdif > 0) do { r--; }while (l < r && num[r + 1] == num[r]); else return target; } else r--; } do{ i++; }while (i < num.size() - 1 && num[i - 1] == num[i]); } return sum; }
[leetcode]3 Sum closest
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。