[Bis pointer] leetcode 16 3Sum Closest

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

        xxsum is a series of questions, and generally have a binary search and hash are two ways this question is close to the required value, the hash will not work, can only use binary search.

        For the sorted array, the number three is first determined that the position of the intermediate number, then the search for the other two numbers around it, if more than the target, then the left and right hand, left hand or right.

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {

        int n = nums.size();
        sort(nums.begin(), nums.end());
        int offset = INT_MAX;
        int res = 0;
        for (int k = 1; k < n - 1; k++)
        {
            int i = 0;
            int j = n - 1;
            while (i < k && j > k)
            {
                int num = nums[k] + nums[i] + nums[j];
                if (abs(target - num) < offset)
                {
                    offset = abs(target - num);
                    res = num;
                }
                if (num == target)
                {
                    return target;
                }
                else if (num > target)
                {
                    j--;
                }
                else
                {
                    i++;
                }
            }
        }
        return res;
    }
};

 

Guess you like

Origin www.cnblogs.com/fish1996/p/11281457.html