class Solution { public: /** * @param nums: an integer array * @param target: An integer * @return: the difference between the sum and the target */ int twoSumClosest(vector<int> &nums, int target) { // write your code here sort(nums.begin(), nums.end()); int i = 0, j = nums.size()-1, dis = INT_MAX; while (i != j) { int temp = nums[i] + nums[j]; dis = min(dis, abs(temp-target)); if (dis == 0) return 0; if (temp > target) j--; else if(temp < target) i++; } return dis; } };
-------------end of file
thanks for reading-------------