A 12ms Easy-understanding Solution


  • 2
    Y
    class Solution {
    public:
        int threeSumClosest(vector<int>& nums, int target) {
            int len = nums.size();
            int sum = 0, minsum = 0;;
            int dif = INT_MAX;
            if(len < 3) {
                for(int i = 0; i < len; i++) sum += nums[i];
                return sum;
            }
            
            int left, right;
            sort(nums.begin(),nums.end());
            
            for(int i = 0; i < (len - 2); i++) {
                left = i + 1;
                right = len - 1;
                while(left < right) {
                    sum = nums[i] + nums[left] + nums[right];
                    if(abs(sum - target) <= dif) {
                        dif = abs(sum - target);
                        minsum = sum;
                    }
                    if(sum > target) right--;
                    if(sum < target) left++;
                    if(sum == target) return minsum;
                }
            }
            return minsum;
        }
    };

Log in to reply
 

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