LeetCode刷题笔记之16.最接近的三数之和

LeetCode刷题笔记之16.最接近的三数之和

题目

在这里插入图片描述

解题方法:排序 + 双指针

将数组排序,枚举a,从a的右边第一位起,借助双指针一个从左一个从右枚举b和c;
a是固定的,b+c>target则c左移;
a是固定的,b+c<target则b右移;
如果这次a+b+c-target小于上次的值。更新这个值。
最后将这个值返回。

代码

package com.leecode;

import java.util.Arrays;

public class Solution16 {
    public int threeSumClosest(int[] nums, int target) {
    	//排序
        Arrays.sort(nums);
        //设置最接近的值。
        int best = 10000000;
        int n = nums.length;
        //枚举a
        for (int i = 0; i < n; i++) {
        	//优化,枚举a的时候避免重复
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            //使用双指针枚举b,c;
            int j = i + 1;
            int k = nums.length - 1;
            while (j < k) {
                int sum = nums[i] + nums[j] + nums[k];
                //如果相等直接返回
                if (sum == target) {
                    return sum;
                }
                //根据绝对值的差值跟新best
                if (Math.abs(sum - target) < Math.abs(best - target)) {
                    best = sum;
                }
                // 如果和大于 target,左移 c 对应的指针
                if (sum > target) {
                    int k0 = k - 1;
                    //移动到下一个不相等的元素
                    while (j < k0 && nums[k0] == nums[k]) {
                        k0--;
                    }
                    k = k0;
                } else {
                	//如果小于target,右移b对应的指针
                    int j0 = j + 1;
                    //移动到下一个不相等的元素
                    while (j0 < k && nums[j0] == nums[j]) {
                        j0++;
                    }
                    j = j0;
                }
            }
        }
        return best;
    }
}

欢迎各位讨论指正!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

峰子大疯子

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

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

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

打赏作者

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

抵扣说明:

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

余额充值