leetcode16 sum closest 双指针+ 排序

链接

链接

code

排序+双指针,应为在使用双指针的过程中利用了数组的单调性,很大程度上减小了时间复杂度,要注意的是ans在初始化时不要太极端,target的最大值是1e4,我们将把ans设为1e5即可

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    
    
    public int threeSumClosest(int[] nums, int target) {
    
    
        Arrays.sort(nums);
        int ans = 100000;
        for (int i = 0; i < nums.length; i++) {
    
    
            int j = i + 1, k = nums.length - 1;
            while (j < k){
    
    
                int sum = nums[i] + nums[j] + nums[k];
                if (Math.abs(sum - target) < Math.abs(ans - target)){
    
    
                    ans = sum;
                }

                if (sum == target){
    
    
                    return target;
                }else if (sum > target){
    
    
                    --k;
                }else{
    
    
                    ++j;
                }
            }
        }
        return ans;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

猜你喜欢

转载自blog.csdn.net/weixin_50070650/article/details/112131832