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

分析

先排序,然后左右夹逼,复杂度 O(n2)O(n^2)

代码

  1. // 3Sum Closest
  2. // 先排序,然后左右夹逼
  3. // Time Complexity: O(n^2), Space Complexity: O(1)
  4. public class Solution {
  5. public int threeSumClosest(int[] nums, int target) {
  6. int result = 0;
  7. int minGap = Integer.MAX_VALUE;
  8. Arrays.sort(nums);
  9. for (int i = 0; i < nums.length - 1; ++i) {
  10. int j = i + 1;
  11. int k = nums.length - 1;
  12. while(j < k) {
  13. final int sum = nums[i] + nums[j] + nums[k];
  14. final int gap = Math.abs(sum - target);
  15. if (gap < minGap) {
  16. result = sum;
  17. minGap = gap;
  18. }
  19. if (sum < target) ++j;
  20. else --k;
  21. }
  22. }
  23. return result;
  24. }
  25. }

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/linear-list/array/3sum-closest.html