1. 程式人生 > >LeetCode(16)—— 最接近的三數之和

LeetCode(16)—— 最接近的三數之和

沒什麼好說的,這就是三數之和的變種。

  1. 先排序
  2. 再確定一個數,用雙指標移動兩個數,比較diff和當前diff值即可。
import java.util.Arrays;


public class ThreeSumClosest16 {
    /***
     * 三數之和的變種,先排序,指定一個值後,再用雙指標
     *
     */
    public int threeSumClosest(int[] nums, int target) {

        int result = nums[0] + nums[1] + nums[2];
        int diff = Math.abs(result - target);
        //  先排序
        Arrays.sort(nums);
        int left, right;
        for (int i = 0; i < nums.length - 2; i++) {
            int current = nums[i];
            // 雙指標,系三數之和變種
            left = i + 1;
            right = nums.length - 1;
            while (left < right) {
                int sum = current + nums[left] + nums[right];
                int newDiff = Math.abs(sum - target);
                if (newDiff < diff) {
                    diff = newDiff;
                    result = sum;
                }
                // 如果當前和比預期的target小,則右移left指標
                if (sum < target)
                    left++;
                else
                    // 否則左移right指標
                    right--;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        ThreeSumClosest16 threeSumClosest16 = new ThreeSumClosest16();
        int[] nums = {-1, 2, 1, -4};
        int target = 1;
        int result = threeSumClosest16.threeSumClosest(nums, target);
        System.out.println(result);
    }
}