码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 016 3Sum Closest

时间:2015-02-07 15:50:51      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

题目描述: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;
        
    }
};

 

LeetCode 016 3Sum Closest

标签:

原文地址:http://www.cnblogs.com/510602159-Yano/p/4278876.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!