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;
        }
    };
  • 相关阅读:
    Swift-自定义类的构造函数
    Swift-存储属性,计算属性,类属性
    iOS-UICollectionViewController协议及回调
    Swift-数组
    Swift-switch使用注意点
    Swift-setValuesForKeysWithDictionary
    解决IDEA Struts2 web.xml问题
    枚举类
    增强for循环 -- foreach循环
    静态导入
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/4873757.html
Copyright © 2011-2022 走看看