zoukankan      html  css  js  c++  java
  • [LeetCode]22. 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).

    解法:与3Sum问题一样,可以通过先确定一个数再转化为2Sum问题,只不过此时两个数之和不是等于target,而是三个数之和最接近target,即2Sum问题的两个数之和最接近target-nums[i](i=0,1,...,n-1)。

    class Solution {
    public:
        int threeSumClosest(vector<int>& nums, int target) {
            int n = nums.size();
            int closest = 0;
            int diff = INT_MAX;
            sort(nums.begin(), nums.end());
            for(int i = 0; i < n - 2; i++)
            {
                int left = i + 1, right = n - 1;
                int tar = target - nums[i];
                while(left < right)
                {
                    int tmp = nums[left] + nums[right];
                    int dist = abs(tar - tmp);
                    if(dist < diff)
                    {
                        diff = dist;
                        closest = nums[i] + nums[left] + nums[right];
                    }
                    if(nums[i] + nums[left] + nums[right] < target)
                        left++;
                    else
                        right--;
                }
            }
            return closest;
        }
    };
    View Code
    class Solution {
    public:
        int threeSumClosest(vector<int>& nums, int target) {
            int n = nums.size();
            int closest = nums[0] + nums[1] + nums[2];
            int diff = abs(closest - target);
            sort(nums.begin(), nums.end());
            for(int i = 0; i < n - 2; i++)
            {
                int left = i + 1, right = n - 1;
                while(left < right)
                {
                    int sum = nums[i] + nums[left] + nums[right];
                    int dist = abs(sum - target);
                    if(dist < diff)
                    {
                        diff = dist;
                        closest = sum;
                    }
                    if(sum < target)
                        left++;
                    else
                        right--;
                }
            }
            return closest;
        }
    };
  • 相关阅读:
    [转]老男孩读pcie
    nand
    面试题目汇总
    redis的tcp-backlog配置
    Redis 3.0.4 sentinels
    Redis 3.0.4 客户端
    Redis 3.0.4 事件驱动
    Redis 3.0.4 AOF持久化
    Redis 3.0.4 数据库
    Redis 3.0.4 RDB持久化
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/4873757.html
Copyright © 2011-2022 走看看