14 ms ,O(N^2) easy understanding c++ solution


  • 0
    Z
    class Solution {
    public:
        int threeSumClosest(vector<int>& nums, int target) {
            int ans=nums[0]+nums[1]+nums[2],len=nums.size();
            sort(nums.begin(),nums.end());
            for(int i=0;i<len-2;i++){
                int sum=target-nums[i];
                int lo=i+1,hi=len-1;
                while(lo<hi){
                    int cur=nums[lo]+nums[hi];
                    if(abs(nums[i]+cur-target)<abs(ans-target))ans=nums[i]+cur;
                    if(cur<sum)lo++;
                    else if(cur>sum)hi--;
                    else return target;
                }
            }
            return ans;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.