zoukankan      html  css  js  c++  java
  • 16. 3Sum Closest(双指针)

    Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

    Example:

    Given array nums = [-1, 2, 1, -4], and target = 1.
    
    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

    class Solution {
    public:
        int threeSumClosest(vector<int>& a, int target) {
            const int n = a.size();
            int res = 0;
            if (n < 3) {
                for (auto& ii :a){
                    res+=ii;
                }
                return res;
            }
            std::sort(a.begin(),a.end());
            res = a[0] + a[1] + a[2];
            for(int i = 0; i < n-2; ++i) {
                int low = i + 1;
                int high = n - 1;
                while(low < high) {
                    int cur_sum = a[i] + a[low] + a[high];
                    if (abs(cur_sum - target) < abs(res - target)) {
                        res = cur_sum;    
                    };
                    if (cur_sum > target) {
                        high--;
                    } else if (cur_sum < target) {
                        low++;
                    } else {
                        return target;
                    }
                }
            }
            return res;
            
        }
    };
     1 class Solution {
     2     public int threeSumClosest(int[] nums, int target) {
     3         int res = nums[0]+nums[1]+nums[2];
     4         Arrays.sort(nums);
     5         for(int i = 0 ; i<nums.length-2;i++){
     6             int lo=i+1,hi=nums.length-1;
     7             while(lo<hi){
     8                 int sum=nums[i]+nums[lo]+nums[hi];
     9                 if(sum>target) hi--;
    10                 else lo++;
    11                 if(Math.abs(sum-target)<Math.abs(res-target))
    12                     res = sum;
    13             }
    14         }
    15         return res;
    16     }
    17 }
  • 相关阅读:
    基于Yarp实现内网http穿透
    让Github畅通无阻,FastGithub1.0.0发布
    Pipeline模式与Factory+Provider模式的应用
    开源FastGithub
    开源Influxdb2高性能客户端
    开源AwaitableCompletionSource,用于取代TaskCompletionSource
    SourceGenerator入门指北
    dotnet高性能buffer
    CURL用法
    Nginx的进程管理与重载原理
  • 原文地址:https://www.cnblogs.com/zle1992/p/9313719.html
Copyright © 2011-2022 走看看