1. 程式人生 > >leetcode題解-16. 3Sum Closest

leetcode題解-16. 3Sum Closest

和 3Sum解題報告很像,但不同的是,不再是求三個數的和是不是為0,而是看三個數的和與target的差是否為最小,只需記錄當前最優解closest並不斷更新其值就可。但是容易出錯的地方是,把 closest 初始值設為 Integer.MAX_VALUE,然後後面計算 closest = Math.abs(closest - target),這樣會導致溢位。

import java.util.Arrays;

class Solution {
    public static int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        // -4,-1,-1,0,1,2
int len = nums.length; int closest = Integer.MAX_VALUE / 2; for(int i = 0; i < len - 2; i++){ int k = len - 1; int j = i + 1; while(j < len - 1 && j < k){ int sum = nums[i] + nums[j] + nums[k]; int
a = Math.abs(closest - target); int b = Math.abs(sum - target); closest = a < b? closest : sum; if(sum < target){ j++; }else if(sum > target){ k--; }else
{ return sum; } } } return closest; } public static void main(String[] args) { int[] nums = {-3,-2,-5,3,-4}; System.out.println(threeSumClosest(nums, -1)); } }