码迷,mamicode.com
首页 > 编程语言 > 详细

LeetCode-3Sum Closest-三数和最近-有序数组逼近

时间:2014-10-19 11:19:59      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   for   sp   

https://oj.leetcode.com/problems/3sum-closest/

和3sum类似。不同的是这次需要逼近一个值,实际上跟相等类似,用l和r指针不断移动,然后反复取最小即可。

class Solution {
public:
    int n,m;
    int threeSumClosest(vector<int> &num, int target) {
        vector<int> &a=num;
        n=a.size();
        sort(a.begin(),a.end());
        int ms=numeric_limits<int>::max();
        int res=-1;
        for(int i=0;i<n;i++){
            int x=a[i];
            int l=i+1,r=n-1;
            while(l<r) {
                int cs=x+a[l]+a[r];
                if (abs(cs-target)<ms) {
                    res=cs;
                    ms=abs(cs-target);
                }
                if(cs <target) l++;
                else r--;
            }
        }
        return res;
    }
};

 

LeetCode-3Sum Closest-三数和最近-有序数组逼近

标签:style   blog   http   color   io   os   ar   for   sp   

原文地址:http://www.cnblogs.com/yangsc/p/4034407.html

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