leetcode --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).
题目大意是:在一个数组里寻找3个数字,这三个数字的和要和target最接近。

思路:先调用sort排序,然后取三个指针,p1从头开始遍历;p2指向p1的下一个,然后依次遍历;p3指向数组尾部;如果*p1+*p2+*p3>targrt,则应该--p3,相反则应该++p2,相等则最好,直接输出。

class Solution {
public:
    int threeSumClosest(vector& nums, int target) {
        sort(nums.begin(),nums.end());
        
        int ret;
        bool first = false;
        
        for(int i = 0; i < nums.size();i++){
            int j = i+1;
            int k = nums.size() -1;
            
            while(j < k){
                int sum = nums[i] + nums[j] + nums[k];
                if(first){
                    ret = sum;
                    first = false;
                }
                else{
                    if(abs(sum - target) < abs(ret -target))
                        ret = sum;
                }
                
                if(ret == target)
                    return ret;
                if(sum > target)
                    k--;
                else
                    j++;
            }
        }
        return ret;
    }
};






你可能感兴趣的:(数据结构与算法)