LeetCode[16]: 3Sum Closest
阿新 • • 發佈:2018-12-17
題目描述
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).
解題思路
這道題和之前的兩數之和的解決方式類似,區別是在其基礎上增加了第三個數。我們可以通過固定其中一個數 ,然後尋找兩數之和最接近 ,將問題轉化為兩數之和的問題。首先將資料排序,遍歷陣列固定
程式碼
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;
}
}