Leetcode 16、最接近的三数之和

Leetcode 16、最接近的三数之和

在这里插入图片描述

排序+指针

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int len = nums.length;
        int res = 10000000;

        for(int i = 0; i < len; i++) {
            if(i != 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            int j = i + 1, k = len - 1;
            while(j < k) {
            	// 如果当前三数之和等于target,直接返回target
                int curr = nums[i] + nums[j] + nums[k];
                if(curr == target) return target;
				
				// 如果当前curr和target的差值小于res和target的差值,更新res。
                if(Math.abs(curr - target) < Math.abs(res - target)) {
                    res = curr;
                }
				
				/**
					如果当前curr的值小于target,因为nums数组已经被排序,所以
					j向右移动到一个新的值的位置
					
					curr大于target的值,则左移k
				**/
                if(curr < target) {
                    int j0 = j + 1;
                    while(j0 < k && nums[j0] == nums[j]) {
                        j0++;
                    }
                    j = j0;
                }else{
                    int k0 = k - 1;
                    while(k0 > j && nums[k0] == nums[k]) {
                        k0--;
                    }
                    k = k0;
                }
            }
        }

        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值