Leetcode 16. 3Sum Closest

16. 3Sum Closest

  • Total Accepted: 85780
  • Total Submissions: 289017
  • Difficulty: Medium

 

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

 

 

思路:将序列升序排序后,设定ans等于a[0],a[1],a[2],然后用三个指针集i,j,k遍历有序序列,sum=a[i]+a[j]+a[k],如果sum>ans,就更新ans。每一轮特定i下关j,k都遍历完后,就比较ans是否等于target,如果等于就返回当前的a[i],a[j],a[k]。

原来还想排序后找到最小的>=target的数A,然后得到由这个数递减的最大的<=target的数B。比较AB和target的接近程度,然后返回相应结果。

 

代码:

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

 

 

 

 

posted @ 2016-07-23 15:37  Deribs4  阅读(252)  评论(0编辑  收藏  举报