LeetCode 16. 3Sum Closest

来源:互联网 发布:远控王远程控制软件 编辑:程序博客网 时间:2024/05/14 18:45

1.题目描述
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).

2. 解题思路
这个题目和之前的3sum有点像,不过这个是找最近似的,所以方法还是和上次一样,排序然后用头尾指针搞
复杂度O(nlogn+n2)
要点是:
如果 当前值优于 最优值, 则更新最优值
3. 代码

#include<cmath>class Solution {public:    int threeSumClosest(vector<int>& nums, int target) {        int res=nums[0]+nums[1]+nums[2];        sort(nums.begin(),nums.end());        for(int i=0;i<nums.size()-2;++i){            int tres;            if(i!=0&&nums[i]==nums[i-1]){                continue;            }            tres=nums[i]+nums[i+1]+nums[i+2];            int rest=target-nums[i];            int head=i+1;            int tail=nums.size()-1;            while(tail>head){                if(nums[head]==nums[head-1]&&head!=i+1){                    ++head;                    continue;                }                if(tail!=nums.size()-1&&nums[tail]==nums[tail+1]){                    --tail;                    continue;                }                if(nums[tail]+nums[head]==rest){                    return target;                }                else if(nums[tail]+nums[head]>rest){                    tres=(abs(nums[tail]+nums[head]+nums[i]-target)<abs(tres-target))?nums[tail]+nums[head]+nums[i]:tres;                    --tail;                }                else{                    tres=(abs(nums[tail]+nums[head]+nums[i]-target)<abs(tres-target))?nums[tail]+nums[head]+nums[i]:tres;                    ++head;                }            }            res=(abs(target-res)>abs(target-tres))?tres:res;        }        return res;    }};
0 0
原创粉丝点击