16 最接近的三数之和 Medium

Problem: 16. 最接近的三数之和

解题方法

枚举每个i,之后利用双指针向中间压缩,以得到距离 t a r g e t target target最近的数值

复杂度

  • 时间复杂度: O ( n 2 ) O(n^2) O(n2)

  • 空间复杂度: O ( 1 ) O(1) O(1)

Code

Python

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        n = len(nums)
        nums.sort()
        ans = inf # 记录的为差值
        for i in range(n - 2):
            # 如果i位置上的数与i-1位置上的数相同
            # 说明i位置能够组合的数已经被i-1包含了
            if i > 0 and nums[i] == nums[i - 1]:
                continue
            # 利用双指针,往中间压缩,
            j = i + 1
            k = n - 1
            while j < k:
                total = nums[i] + nums[j] + nums[k]
                if total < target:
                    j += 1
                elif total == target:
                    return target
                else:
                    k -= 1
                if abs(total - target) < abs(ans - target):
                    ans = total
        return ans

Java

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int n = nums.length;
        int ans = 100000000;
        for(int i = 0; i < n - 2; i++){
            if(i > 0 && nums[i] == nums[i - 1]){
                continue;
            }
            int left = i + 1;
            int right = n - 1;
            while(left < right){
                int total = nums[i] + nums[left] + nums[right];
                if(total == target){
                    return total;
                }
                else if(total > target){
                    right--;
                }
                else{
                    left++;
                }
                if(Math.abs(total - target) < Math.abs(ans - target)){
                    ans = total;
                }
            }
        }
        return ans;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值