题目:
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).
链接:https://leetcode.com/problems/3sum-closest/#/description
4/9/2017
23ms, 65%
注意的问题:
1. sum初始值可以设的大,但是第7行一定不能遗漏,否则之后可能有溢出。
2. performance注意主要是在big O,其他多少毫秒意义有限,可以和别人的对比,但是有时候别人的答案也只是简单处理了invalid input,未必比自己的更好。
1 public class Solution { 2 public int threeSumClosest(int[] nums, int target) { 3 if (nums.length < 3) return Integer.MAX_VALUE; 4 5 Arrays.sort(nums); 6 int sum = nums[0] + nums[1] + nums[2]; 7 for (int i = 0; i < nums.length - 2; i++) { 8 int lo = i + 1, hi = nums.length - 1; 9 while (lo < hi) { 10 int value = nums[i] + nums[lo] + nums[hi]; 11 if (value == target) return target; 12 if (Math.abs(value - target) < Math.abs(sum - target)) sum = value; 13 if (value > target) hi--; 14 else lo++; 15 } 16 } 17 return sum; 18 } 19 }