1. 程式人生 > >LeetCode[16]: 3Sum Closest

LeetCode[16]: 3Sum Closest

題目描述

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

For example, given array S = {-1 2 1 -4}, and target = 1.

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

解題思路

這道題和之前的兩數之和的解決方式類似,區別是在其基礎上增加了第三個數。我們可以通過固定其中一個數 n u m s i ,然後尋找兩數之和最接近

t a r g e t n u m s i ,將問題轉化為兩數之和的問題。首先將資料排序,遍歷陣列固定
n u m s i 然後使 j = i + 1 k = l e n g t h 1 ,通過移動 j k 兩個下標,來使 n u m s j + n u m s k t a r g e t n u m s i 。然後儲存當前最優解和當前三數之和更接近目標target的值。

程式碼

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        int threeSum = nums[0] + nums[1] + nums[2];
        int closestNum = threeSum;
        //先排序
        Arrays.sort(nums);
        for (int i=0; i < nums.length-2; i++) {
            int twoSum = target - nums[i];
            int j = i + 1, k = nums.length-1;
            while (j < k) {
                threeSum = nums[i] + nums[j] + nums[k];
                if(Math.abs(threeSum-target) < Math.abs(closestNum-target))
                    closestNum = threeSum;
                if (nums[j] + nums[k] < twoSum) {
                    j++;
                } else if (nums[j] + nums[k] > twoSum) {
                    k--;
                } else { return target; }
            }
        }
        return closestNum;
    }
}