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

思路

目的:找到三个数的和最接近target。

排序,从小到大,使与target之差值越来越小。i,j最小,k最大,然后去找合适值。

  1. 如果三个数之和大于target,判断之差是否比目前最小差更小,更小就更新结果以及最小差,同时将j增大。
  2. 反之同理。
  3. 相等就是了。

代码

class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
    if (nums.size() < 3)
    {
        return -1;
    }
    int res = 0;//最后答案
    int distance = INT_MAX;//总的最近的差,包括大的和小的
    int i, j, k;
    sort(nums.begin(),nums.end());//先排序
    for (i = 0; i < nums.size() - 2; i++)
    {
        j = i + 1;
        k = nums.size() - 1;
        while (j < k)
        {
            int temp = nums[i] + nums[j] + nums[k];
            int temp_distance;
            if (temp < target)//说明太小了,要变大
            {
                temp_distance = target - temp;//当前三个值与target的差
                if (temp_distance < distance)//更接近了可以进行更新
                {
                    res = temp;
                }
                j++;
            }
            else if(temp > target)
            {
                    temp = nums[i] + nums[j] +     nums[k];
                    temp_distance = temp - target;
                if (temp_distance < distance)
                {
                res = temp;
                }
                k--;
            }
            else
            {
                temp = nums[i] + nums[j] + nums[k];
                res = temp;
            }
        }
    }
    }
};
posted @ 2017-07-31 22:42  云胡同学  阅读(74)  评论(0编辑  收藏  举报