原题链接在这里:https://leetcode.com/problems/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).
题解:
与3Sum类似,这里不用去掉重复的值,因为这里不需要避免存入重复的值。
基本思路就是维护一个最小的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; i<nums.length-2; i++){ 11 int j = i+1; 12 int k = nums.length-1; 13 while(j<k){ 14 if(Math.abs(nums[i] + nums[j] + nums[k] - target) < diff){ 15 diff = Math.abs(nums[i] + nums[j] + nums[k] - target); 16 sum = nums[i] + nums[j] + nums[k]; 17 } 18 19 if(nums[i] + nums[j] + nums[k] < target){ 20 j++; 21 }else if(nums[i] + nums[j] + nums[k] > target){ 22 k--; 23 }else{ 24 return sum; 25 } 26 } 27 } 28 return sum; 29 } 30 }