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

问题:

解:

package com.example.demo;

import java.util.Arrays;

public class Test16 {

    /**
     * 给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,
     * 使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
     *
     * @param nums
     * @param target
     * @return
     */
    public int threeSumClosest(int[] nums, int target) {
        /*
            排序+双指针
            先使用排序,将nums数据排好,让后定义两个指针,分别指向当前位置的下一个和最后一个数字,
            然后将三个数的和  跟target比较
         */
        Arrays.sort(nums);

        int res = nums[0] + nums[1] + nums[2];
        for (int i = 0; i < nums.length; i++) {
            int left = i + 1;
            int right = nums.length - 1;
            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (Math.abs(target - sum) < Math.abs(target - res)) {
                    res = sum;
                }
                if (sum > target) {
                    right--;
                } else if (sum < target) {
                    left++;
                } else {
                    return res;
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        Test16 t = new Test16();
        int[] arr = {0, 2, 1, -3};
        int i = t.threeSumClosest(arr, 1);
        System.out.println(i);
    }
}

猜你喜欢

转载自www.cnblogs.com/nxzblogs/p/11245497.html