首页 > 代码库 > LeetCode-3Sum Closest-三数和最近-有序数组逼近

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

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-三数和最近-有序数组逼近