Two Sum Closest

题目:

Given an array nums of n integers, find two integers in nums such that the sum is closest to a given number, target.

Return the difference between the sum of the two integers and the target.

分析:

这是一个典型的碰撞指针问题。

解法:

class Solution {
public:
    /**
     * @param nums an integer array
     * @param target an integer
     * @return the difference between the sum and the target
     */
    int twoSumCloset(vector<int>& nums, int target) {
        // Write your code here
        int minDiff = INT_MAX;
        int start = 0;
        int end = nums.size() - 1;
        sort(nums.begin(), nums.end() );
        while (start < end) {
            int sum = nums[end] + nums[start];
            minDiff = min(minDiff, abs(sum - target) );
            if (sum > target) {
                end--;
            } else {
                start++;
            }
        }
        return minDiff;
    }
};

results matching ""

    No results matching ""