Array + two points leetcode.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.

给定数组,找出并返回最接近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 };

转载于:https://www.cnblogs.com/yocichen/p/10862763.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值