[Leetcode]3Sum Closest

来源:互联网 发布:055型驱逐舰知乎 编辑:程序博客网 时间:2024/06/05 02:49

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).
Have you met this question in a real interview?
 
class Solution {public:    /*algorithm: two pointers    */    int threeSumClosest(vector<int>& nums, int target) {        int size = nums.size();        long minSum = INT_MAX;        sort(nums.begin(),nums.end());        for(int i = 0;i < size - 2;i++){            int l=i+1,r = size-1;            while(l < r){                int sum = nums[i] + nums[l]+nums[r];                if(abs(sum - target) < abs(minSum-target)){                    minSum = sum;                }                if(sum == target)return target;                else if(sum < target)l++;                else r--;            }        }                return minSum;    }};

0 0