zoukankan      html  css  js  c++  java
  • 16. 最接近的三数之和 O(N^2)

    给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。

    例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.

    与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

    思路就是先枚举一个数字,然后用尺取确定另外两个数字。

    class Solution {
    public:
        int threeSumClosest(vector<int>& nums, int target) {
            int siz =  nums.size();
            sort(nums.begin(),nums.end());
            int res=nums[siz-1]+nums[siz-2]+nums[siz-3];
            for(int i=0;i<siz-2;++i){
                int l=i+1,r=siz-1;
                int temp = nums[i]+nums[l]+nums[r];
                if(abs(target-temp)<abs(target-res))res=temp;
                while(l<r){
                     if(r-l+1<=2)break;
                     if(temp<target)temp-=nums[l],temp+=nums[++l];
                     else if(temp>target&&r>l)temp-=nums[r],temp+=nums[--r];
                     if(temp==target)return target;
                     if(abs(target-temp)<abs(target-res))res=temp;
                    // cout<<temp<<' '<<l<<' '<<r<<endl;
                }
            }
            return res;
        }
    };
    

      

  • 相关阅读:
    NOI 模拟赛
    bzoj 4998 星球联盟
    bzoj 4545 DQS 的 Trie
    loj #161 子集卷积
    bzoj 5093 图的价值
    bzoj 4299 Codechef FRBSUM
    NOI 模拟赛
    WC2018 州区划分
    CSP 2020 T2 动物园
    CSP 2020 T1 儒略日
  • 原文地址:https://www.cnblogs.com/DreamKill/p/12590452.html
Copyright © 2011-2022 走看看