3Sum Closest

来源:互联网 发布:java基础知识体系结构 编辑:程序博客网 时间:2024/05/20 15:38

本文转载自:http://blog.csdn.net/doc_sgl/article/details/12461893


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).
  1. int threeSumClosest(vector<int> &num, int target) {  
  2.         // Start typing your C/C++ solution below  
  3.         // DO NOT write int main() function  
  4.         int numlen = num.size();  
  5.         if(numlen<3)return -1;  
  6.   
  7.         sort(num.begin(),num.end());  
  8.         int minGap = num[0]+num[1]+num[2]-target;  
  9.         for(int i = 0; i <= numlen-3; i++)  
  10.         {  
  11.             int begin = i+ 1;  
  12.             int end = numlen-1;  
  13.             while(begin < end)  
  14.             {  
  15.                 int curGap = num[i]+num[begin]+num[end]-target;  
  16.                 if(curGap == 0) return target;  
  17.                 if(abs(curGap) < abs(minGap)) minGap = curGap;  
  18.                 if(curGap < 0)   begin++;  
  19.                 else end--;  
  20.             }  
  21.         }  
  22.         return target+minGap;  
  23.     }  

0 0
原创粉丝点击