原题链接在这里:
题目:
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).
题解:
与类似,这里不用去掉重复的值,因为这里不需要避免存入重复的值。
基本思路就是维护一个最小的diff,排序之后夹逼。
Time Complexity: O(n^2), sort takes O(n*logn), for loop 中的每一个 i 后的while loop 用了O(n) time.
Space Complexity is O(1).
AC Java:
1 public class Solution { 2 public int threeSumClosest(int[] nums, int target) { 3 if(nums == null || nums.length < 3){ 4 return Integer.MIN_VALUE; 5 } 6 7 Arrays.sort(nums); 8 int diff = Integer.MAX_VALUE; 9 int sum = 0;10 for(int i = 0; itarget){22 k--;23 }else{24 return sum;25 }26 }27 }28 return sum;29 }30 }