ARTS WEEK 9

Posted by Eric Jin on 2019-10-30

Algorithm

Description

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example: 

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

solution

思路: 把数组排序,排序以后遍历数组,然后维持两个指针。左指针指在遍历index后一个,右指针指在数组末尾,求出三数的结果比较最小值。 在这里,在外层的while 循环中又套了while 循环,用来对相同的数字进行跳过。每一次结果之后,比较当前的三数和与之前的三数和。 如果三数和与目标数相同可以直接返回,因为这样的三数差额肯定是最小的(0)

public int threeSumClosest(int[] nums, int target) {
    Arrays.sort(nums);
    int len = nums.length;
    int ans = nums[0] + nums[1] + nums[2];
    for (int i = 0; i < len - 2; i++) {
        int left = i + 1, right = len - 1;
        while (left < right) {
            int sum = nums[i] + nums[left] + nums[right];
            if (sum > target) {
                while (left < right && nums[right] == nums[right - 1])
                    right--;
                right--;
            } else if (sum < target) {
                while (left < right && nums[left + 1] == nums[left])
                    left++;
                left++;
            } else {
                return sum;
            }
            if (Math.abs(sum - target) < Math.abs(ans - target)) {
                ans = sum;
            }
        }
    }
    return ans;
}

Review

Tips

关于 git 中reset的用法简介

Share