首页 > 其他 > 详细

3Sum Closest

时间:2015-07-08 22:31:34      阅读:233      评论:0      收藏:0      [点我收藏+]

Question:

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.

技术分享

Solution:

 1 class Solution {
 2 public:
 3     int threeSumClosest(vector<int>& nums, int target) {int result=0;
 4     if(nums.size()<3)
 5         return result;
 6     sort(nums.begin(),nums.end());
 7     int gap=abs(nums[0]+nums[1]+nums[2]-target);
 8     auto last=nums.end();
 9     for(auto i=nums.begin();i<last-2;i++)
10     {
11         auto j=i+1;
12         auto k=last-1;
13         while(j<k)
14         {
15             if(abs(*i+*j+*k-target)<=gap)
16             {
17                 result=*i+*j+*k;
18                 gap=abs(*i+*j+*k-target);
19             }
20             if((*i+*j+*k)<target)
21                 j++;
22             else k--;
23         }
24     }
25     return result;
26         
27     }
28 };

技术分享

3Sum Closest

原文:http://www.cnblogs.com/riden/p/4631471.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!