LeetCode-016 3Sum Closest

来源:互联网 发布:衣服软件 编辑:程序博客网 时间:2024/05/20 07:53

Description

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.

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).

Analyse

这道题跟上一道题很像,解法也差不多,也是排序,选一个数,然后前后往中间找出两个数,使得他们之和最接近目标值。

Code

class Solution {public:    int threeSumClosest(vector<int>& nums, int target) {        if (nums.size()<3) return 0;        int close=INT_MAX;        int ans;        sort(nums.begin(),nums.end());        for (int i=0;i<nums.size()-2;i++) {            int p=i+1,q=nums.size()-1;            while (p<q) {                int sum=nums[i]+nums[p]+nums[q];                if (sum<target) {                    if (target-sum<close) {                        close=target-sum;                        ans=sum;                    }                    p++;                } else {                    if (sum>target) {                        if (sum-target<close) {                            close=sum-target;                            ans=sum;                        }                        q--;                    } else {                        return sum;                    }                }            }        }        return ans;    }};
原创粉丝点击