3Sum Closest

来源:互联网 发布:棋牌源码有什么用 编辑:程序博客网 时间:2024/05/17 23:43

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.
思路:这道题目的做法与3Sum的做法大致相同,只不过需要增加一个标记来记录每一次比较的最接近的值即可,代码如下:

class Solution {public:    int threeSumClosest(vector<int>& nums, int target) {        int len = nums.size(), i, j, k, closest = 0, delta = 2147483647;        if(len == 3)            return nums[0] + nums[1] +nums[2];        sort(nums.begin(), nums.end());        for(i = 0; i < len - 2; ++i){            if(i > 0 && nums[i] == nums[i - 1])                continue;            j = i + 1;            k = len - 1;            while(j < k){                if(j > i + 1 && nums[j] == nums[j - 1]){                    j++;                    continue;                }                if(k < len - 1 && nums[k] == nums[k + 1]){                    k--;                    continue;                }                int sum = nums[i] + nums[j] + nums[k];                int tmpDelta = abs(sum-target);                if(delta > tmpDelta){                    delta = tmpDelta;                    closest = sum;                }                if(sum < target)                    j ++;                else if(sum > target)                    k --;                else{                    return sum;                }            }        }        return closest;    }};
0 0
原创粉丝点击