数组类16--最接近的三数之和(M)

image.png

AC代码

import java.util.*;


class Solution {
    private int min = Integer.MAX_VALUE;
    private int ans = Integer.MAX_VALUE;

    private void updateMin(int a, int b, int c, int target) {
        int tmp = abs(a + b + c - target);
        if (tmp < min) {
            min = tmp;
            ans = a + b + c;
        }
    }

    public int threeSumClosest(int[] nums, int target) {
        if (nums == null || nums.length < 3) {
            return Integer.MAX_VALUE;
        }
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 2; i++) {
            int tmpTarget = target - nums[i];
            int left = i + 1;
            int right = nums.length - 1;
            while (left < right) {
                //0
                if (nums[left] + nums[right] == tmpTarget) {
                    return target;
                } else if (nums[left] + nums[right] < tmpTarget) {
                    updateMin(nums[i], nums[left], nums[right], target);
                    left++;
                } else {
                    updateMin(nums[i], nums[left], nums[right], target);
                    right--;
                }
            }
        }
        return ans;

    }

    private int abs(int a) {
        if (a >= 0) {
            return a;
        } else {
            return -a;
        }
    }
}

精髓
1.依然是two pointers

你可能感兴趣的:(数组类16--最接近的三数之和(M))