1. 程式人生 > >【LeetCode】16. 3Sum Closest - Java實現

【LeetCode】16. 3Sum Closest - Java實現

文章目錄

1. 題目描述:

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).

2. 思路分析:

題目的意思是給定一個數組和一個目標數,找到陣列中的3個數使得這3個數的和與目標數最接近(即:差的絕對值最小),並返回該3個數的和。

該題的思路類似3Sum的解法思路,但需要維護一個當前與目標值最近的值。

3. Java程式碼:

原始碼見我GiHub主頁

程式碼:

public static
int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int minDistance = Integer.MAX_VALUE; int result = 0; for (int i = 0; i < nums.length; i++) { int left = i + 1; int right = nums.length - 1; while (left < right) { int threeSum = nums[
i] + nums[left] + nums[right]; if (threeSum == target) { return threeSum; } if (threeSum < target) { left++; } if (threeSum > target) { right--; } int curDistance = Math.abs(threeSum - target); if (curDistance < minDistance) { minDistance = curDistance; result = threeSum; } } } return result; }