LeetCode 16. 3Sum Closest

来源:互联网 发布:成都买车位划算 知乎 编辑:程序博客网 时间:2024/06/07 03:28

3Sum Closest


题目描述:

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


题目大意:

给定一个数组nums和一个数字target。找出nums中三个数字的和最接近target的情况,并且返回这三个数字的和。
固定第一个数字,用两个指针一个从前面开始往后遍历,另一个从后面开始从前面开始遍历。
如果恰好有3个数的和等于target那么直接返回taeget结束操作即可。否则一只到遍历完成找出最接近target的结果。


题目代码:

class Solution {public:    int threeSumClosest(vector<int>& nums, int target) {        sort(nums.begin(), nums.end());        int l, r; long ans = INT_MAX;        for(int i = 0; i < nums.size(); i++){            l = i+1; r = nums.size()-1;                        while(l < r){                int sum = nums[i] + nums[l] + nums[r];                if(sum == target){                    return target;                }else if(sum < target){                    l++;                }else{                    r--;                }                if(abs(ans - target) > abs(target-sum))                    ans = sum;            }             }        return (int)ans;    }};