[LintCode] 3 Sum Closest
public int threeSumClosest(int[] numbers ,int target) { // write your code here Arrays.sort(numbers); if(numbers.length == 0 || numbers == null) return 0; int close = Integer.MAX_VALUE; for(int i = 0; i < numbers.length - 2; i++) { int j = i + 1; int k = numbers.length - 1; while(j < k) { int sum = numbers[i] + numbers[j] + numbers[k]; if(sum == target) return target; else if (sum > target) k--; else j++; if(Math.abs(target - sum) < Math.abs(target - close)) close = sum; } } return close; }
Leave A Comment