lc16最接近的三数之和

16 篇文章 0 订阅
15 篇文章 0 订阅

思路就是转化等式

保证Math.abs(nums[i]+num[l]+nums[r]-target)最小就行,然后i是一层遍历,l,r是双指针,所以时间复杂度为o(n2)。首先是需要排序的!

代码如下:

package com.codeking.lc;

/**
 * @author xiongjl
 * @since 2023/9/17  17:35
 */
public class lc16 {
    public static void main(String[] args) {

        //int[] nums = {1,1,-1};
        //int[] nums = {-1000, -5, -5, -5, -5, -5, -5, -1, -1, -1};
        int[] nums = {-1,2,1,-4};
        lc16 lc16 = new lc16();
        int i = lc16.threeSumClosest(nums, 1);
        System.out.println(i);
    }

    public int threeSumClosest(int[] nums, int target) {
        // 先排序
        quickSort(nums, 0, nums.length - 1);
        int sum, ans = nums[0] + nums[1] + nums[2];
        for (int i = 0; i < nums.length - 2; i++) {
            int l = i + 1, r = nums.length - 1;
            sum = nums[i] + nums[l] + nums[r];
            while (l < r) {
                if (Math.abs(sum - target) < Math.abs(ans-target)) {
                    ans = sum;
                }
                if (sum > target) {
                    r--;
                } else if (sum < target) {
                    l++;
                } else {
                    return sum;
                }
                sum = nums[i] + nums[l] + nums[r];
            }
        }
        return ans;
    }


    private static void quickSort(int[] nums, int l, int r) {
        if (l >= r) {
            return;
        }
        // 中心点,右边开始走,换左边开始走
        int pivot = nums[l];
        int left = l, right = r;
        while (left < right) {
            while (left < right && nums[right] >= pivot) right--;
            if (left < right && nums[right] < pivot) nums[left] = nums[right];
            while (left < right && nums[left] <= pivot) left++;
            if (left < right && nums[left] > pivot) nums[right] = nums[left];
        }
        // 更新中心点
        nums[left] = pivot;
        // 递归
        quickSort(nums, l, right - 1);
        quickSort(nums, right + 1, r);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值