Leetcode1-100: 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.

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

这题的要求跟上一题很相似,找出一个三元组的和,使得这个和最接近这个target

解题思路

  1. Brute force 生成所有三元组,然后判断和是否是最接近的值
  2. 排序扩展法, 先排序,确定一个元素之后,确定后面两个元素来判断能否更新最接近的值。由于先排序了,可以用头尾指针线性的过一遍就可以。这题不需要判断是否重复,所以直接判断即可。

代码实现

        public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int res = Integer.MAX_VALUE - nums[nums.length - 1];
        for(int i = 0; i < nums.length - 2; i++) {
            int start = i + 1, end = nums.length - 1, sum = target - nums[i];
            while(start < end) {
                int tmp = nums[start] + nums[end];
                //判断能否更新sum的情况
                if(Math.abs(tmp - sum) < Math.abs(res-target)) res = tmp + nums[i];
                if(tmp > sum) {
                    while(end >= 1 && nums[end] == nums[end - 1]) end--;
                    end--;
                } else if(tmp < sum) {
                    while(start < nums.length - 1 && nums[start] == nums[start + 1]) start++;
                    start++;
                } else {
                    return target;
                }
            }
        }
        return res;
    }

在这里插入图片描述

复杂度分析

对于实现1的brute force方法,时间复杂度是O(n3)(这里直接判断即可,三层循环里面是O(1)的时间),空间复杂度是O(1)
对于实现2的方法, 时间复杂度是O(n2), 空间复杂度是O(1)

分析

这题跟上一题很相似,实现方法也很类似。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值