LeetCode-16-最接近的三数之和

Posted by 刘知安 on 2019-03-13
文章目录

没什么好说的,这就是三数之和的变种。

  1. 先排序
  2. 再确定一个数,用双指针移动两个数,比较diff和当前diff值即可。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    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);
    }
    }