Topic
- Array
- Two Pointers
Description
https://leetcode.com/problems/3sum-closest/
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 1:
Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Constraints:
- 3 <= nums.length <= 10³
- -10³ <= nums[i] <= 10³
- -10⁴ <= target <= 10⁴
Analysis
方法一:我写的,受到LeetCode - Medium - 15. 3Sum启发而写,幸运成功地成功验收。与方法二相比,代码中的相关跳过重复元素意义的代码是可以去掉的。
方法二:别人写的。比方法一精简了不少。
Submission
import java.util.Arrays;
public class ThreeSumClosest {
// 方法一:我写的
public int threeSumClosest1(int[] nums, int target) {
if (nums == null || nums.length < 3)
throw new IllegalArgumentException();
Arrays.sort(nums);
int closestSum = nums[0] + nums[1] + nums[nums.length - 1];
int minDistance = Integer.MAX_VALUE;
for (int i = 0; i < nums.length - 2; i++) {
if (i == 0 || nums[i] != nums[i - 1]) {
int left = i + 1, right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
int diff = target - sum;
int distance = Math.abs(diff);
if (diff == 0)
return sum;
if (distance < minDistance) {
closestSum = sum;
minDistance = distance;
}
if (diff < 0) {
while (left < right && nums[right] == nums[right - 1])
right--;
right--;
} else if (diff > 0) {
while (left < right && nums[left] == nums[left + 1])
left++;
left++;
}
}
}
}
return closestSum;
}
// 方法二:别人写的,比方法一
public int threeSumClosest2(int[] num, int target) {
int result = num[0] + num[1] + num[num.length - 1];
Arrays.sort(num);
for (int i = 0; i < num.length - 2; i++) {
int start = i + 1, end = num.length - 1;
while (start < end) {
int sum = num[i] + num[start] + num[end];
if (sum > target) {
end--;
} else {
start++;
}
if (Math.abs(sum - target) < Math.abs(result - target)) {
result = sum;
}
}
}
return result;
}
}
Test
import static org.junit.Assert.*;
import org.junit.Test;
public class ThreeSumClosestTest {
@Test
public void test() {
ThreeSumClosest obj = new ThreeSumClosest();
assertEquals(2, obj.threeSumClosest1(new int[] {-1, 2, 1, -4}, 1));
assertEquals(2, obj.threeSumClosest2(new int[] {-1, 2, 1, -4}, 1));
}
}
来源:oschina
链接:https://my.oschina.net/jallenkwong/blog/4873079