Leetcode 16. 3Sum Closest [medium][java]

本文探讨了在给定整数数组中寻找三个数,使其和最接近特定目标值的问题。提供了两种解决方案,均采用排序加双指针策略,时间复杂度为O(n^2),空间复杂度为O(1)。通过实例演示了算法的实现过程。
  1. 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
在这里插入图片描述

Solution 1
Time Complexity: O(n^2), Space Complexity:O(1)

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        
        Arrays.sort(nums);
        int res = nums[0]+nums[1]+nums[2];
        int diff = Math.abs(res-target);
        
        for(int i = 0; i < nums.length-2; i++) {
            if( i > 0 && nums[i-1]==nums[i])
                continue;

            if(res == target)
                break;
            
            int begin = i+1;
            int end = nums.length-1;
            while(begin < end) {
                int sum = nums[i]+nums[begin]+nums[end];
                int newDiff = Math.abs(sum-target) ;
                if(newDiff < diff) {
                    res = sum;
                    diff = newDiff;
                }
                    
                if(sum>target) {
                    end--;
                } else if(sum == target){
                    break;
                } else { 
                    begin++;
                }
            }
        }
        return res;
        
    }
}

Solution 2: improved a little bit by passing the duplicate case
Time Complexity: O(n^2), Space Complexity:O(1)

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        
        Arrays.sort(nums);
        int res = nums[0]+nums[1]+nums[2];
        int diff = Math.abs(res-target);
        
        for(int i = 0; i < nums.length-2; i++) {
            if( i > 0 && nums[i-1]==nums[i])
                continue;

            int begin = i+1;
            int end = nums.length-1;
            while(begin < end) {
                int sum = nums[i]+nums[begin]+nums[end];
                int newDiff = Math.abs(sum-target) ;
                if(newDiff < diff) {
                    res = sum;
                    diff = newDiff;
                }
                    
                if(sum>target) {
                    end--;
                    while(begin<end && nums[end+1]==nums[end])
                        end--;                    
                } else if(sum == target){
                    return res;
                } else { 
                    begin++;
                    while(begin<end && nums[begin]==nums[begin-1])
                        begin++;
                }
            }
        }
        return res;
        
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值