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

    问题:给定一个数组和一个整数 n ,求数组中的三个元素,他们的和离 n 最近。

    这道题和 3Sum 很相似,解题思路也很相似,先排序,然后采用双指针法依次比较。

    由于 3Sum 很相似,思路就不详说。主要说下不同点:

    1. 由于是求最接近值,当 s[i] + s[l] + s[r] - target == 0 的时候,即可返回结果。
    2. 返回的结果是最接近 n 的三个元素之和。
     1 int threeSumClosest(vector<int>& nums, int target) {
     2     
     3     std::sort(nums.begin(), nums.end());
     4     
     5     int closest = target - nums[0] - nums[1] - nums[2];
     6     
     7     for (int i = 0 ; i < nums.size(); i++) {
     8         
     9         int l = i + 1;
    10         int r = (int)nums.size() - 1;
    11         
    12         int newTarget = target - nums[i];
    13         
    14         while (l < r) {
    15             if (nums[l] + nums[r] == newTarget) {
    16                 return target;
    17             }
    18             
    19             int diff = newTarget - nums[l] - nums[r];
    20             if (abs(diff) < abs(closest)) {
    21                 closest = diff;
    22             }
    23             
    24             if (nums[l] + nums[r] < newTarget){
    25                 l++;
    26             }else{
    27                 r--;
    28             }
    29         }
    30     }
    31     
    32     return target - closest;
    33 }
  • 相关阅读:
    【Xamarin破解补丁找不到?】
    【Xamarin挖墙脚系列:Xamarin.Android的API设计准则】
    【给你几个使用Xamarin的理由】
    【Xamarin 跨平台机制原理剖析】
    HttpStatusCode 枚举
    C语音--static变量
    extern "c"用法
    C语言---类型转换
    VS2008资源问题解决方法
    003---hibernate主要接口介绍
  • 原文地址:https://www.cnblogs.com/TonyYPZhang/p/5077386.html
Copyright © 2011-2022 走看看