zoukankan      html  css  js  c++  java
  • Array + two points leetcode.16

    题面

    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.

    给定数组,找出并返回最接近target的三个元素的和。可以假设,只有一个解。

    样例

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

    思路

    我们在15题 3Sum 中做过,三数加和为target的问题,采用了Two-Point逼近的方法。本题我们稍加改动就可以解决。

    1. 数组排序,固定一个元素i,通过两点法去[i+1, size()-1]中搜索另外两个数字,先计算他们的和;

    2. 若sum == target,直接返回;若不等,就需要判断sum与 我们给的初值res 那个更加接近target,即判断 abs(sum - target)  与 abs(res - target)的大小,对res进行更新,另外注意 l 和 r 的更新。

    3. 返回res.

    源码

     1 class Solution {
     2 public:
     3     int threeSumClosest(vector<int>& nums, int target) {
     4         int len = nums.size();
     5         if(len < 3)
     6             return 0;
     7         //数组升序排序
     8         sort(nums.begin(), nums.end());
     9         int res = nums[0]+nums[1]+nums[2];
    10         for(int i=0; i<len; i++)
    11         {
    12             if(i>0 && nums[i]==nums[i-1])
    13                 i++;//避免i的重复,不必要
    14             int l = i+1, r = len-1;
    15             while(l < r)//两点法搜搜
    16             {
    17                 int sum = nums[i] + nums[l] + nums[r];
    18                 if(sum == target)
    19                     return sum;
    20                 else if(sum > target)
    21                 {
    22                     if(abs(sum - target) < abs(res - target))
    23                         res = sum;
    24                     r--;
    25                 }
    26                 else
    27                 {
    28                     if(abs(sum - target) < abs(res - target))
    29                         res = sum;
    30                     l++;
    31                 }
    32             }
    33         }
    34         return res;
    35     }
    36 };
  • 相关阅读:
    240 Search a 2D Matrix II 搜索二维矩阵 II
    239 Sliding Window Maximum 滑动窗口最大值
    bzoj5029: 贴小广告&&bzoj5168: [HAOI2014]贴海报
    bzoj5178: [Jsoi2011]棒棒糖
    bzoj5293: [Bjoi2018]求和
    bzoj5194: [Usaco2018 Feb]Snow Boots
    bzoj2007: [Noi2010]海拔
    bzoj4956: [Wf2017]Secret Chamber at Mount Rushmore
    bzoj3296: [USACO2011 Open] Learning Languages
    bzoj4887: [Tjoi2017]可乐
  • 原文地址:https://www.cnblogs.com/yocichen/p/10862763.html
Copyright © 2011-2022 走看看