[leetcode]16. 3Sum Closest

556 篇文章 2 订阅
441 篇文章 0 订阅

Description

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).

分析

  • 这道题对一开始上手的人来说,可能思维不难,但是代码写好的话,就有点困难,比如在寻找之前先从小到大排序,用diff来记录目标和最近的差值,然后遍历寻找。
  • for(){
    while(left<right){
    }
    }
    这种模式在leetcode的其他几个题中会遇见,这可以作为这一类题目的通用解法。
  • 解法有点暴力

C++ 代码

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(),nums.end());
        int closet=nums[0]+nums[1]+nums[2];
        int diff=abs(closet-target);
        for(int i=0;i<nums.size()-2;i++){
            int left=i+1;
            int right=nums.size()-1;
            while(left<right){
                int sum=nums[i]+nums[left]+nums[right];
                if(diff>abs(sum-target)){
                    diff=abs(sum-target);
                    closet=sum;
                }
                if(sum<target){
                    left++;
                }else{
                    right--;
                }
            }
        }
        return closet;
    }
};

Python 代码

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums.sort()
        res = 2**31
        for i in range(len(nums)):
            if i>0 and nums[i]==nums[i-1]:
                continue
            left = i+1
            right = len(nums)-1
            while left<right:
                val = nums[i]+nums[left]+nums[right]
                if abs(val-target)<abs(res-target):
                    res = val
                
                if val>target:
                    right-=1
                elif val<target:
                    left+=1
                else:
                    return target
        return res

参考文献

[LeetCode] 3Sum Closest 最近三数之和

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值