Source of the topic:
https://leetcode.com/problems/3sum-closest/
Test Instructions Analysis:
This topic input an array of nums and a number of target, find the array of three numbers, make them and closest to target, return these three numbers of the and.
Topic Ideas:
This topic is similar to the previous 3Sum, so it is possible to solve this problem in a comparable way. The whole process is divided into two steps:
① array sorting; This step time complexity is (O (NLOGN)).
② fixed a number, the time complexity of this step is (O (n)).
③ in the remaining number through the "pinch theorem", find out two numbers, make three number and closest to target. The time complexity of this step is (O (n))
The total time complexity is (O (nlogn) + O (n) *o (n)) = (O (n^2)).
Optimization: In the third step, by judging whether the remaining number of the smallest number of two added is greater than or the maximum two number is less than the target-the first number, if so, then directly determine the smallest (large) two and the number of the ② is the closest value.
Code (Python):
1 classsolution (object):2 defthreesumclosest (self, Nums, target):3 """4 : Type Nums:list[int]5 : Type Target:int6 : Rtype:int7 """8Size =Len (nums)9 ifSize < 3:Ten return0 One Nums.sort () Ai = 0#fix The first index -Ans = nums[0] + nums[1] + nums[size-1]#ans is used to record the solution - whileI < size-2: theTMP = target-Nums[i] -j = i + 1 -K = size-1 - whileJ <K: + ifNUMS[J] + nums[k] = =tmp: - returnTarget + ifNUMS[J] + nums[k] >tmp: A ifNUMS[J] + nums[j + 1] >=tmp: at ifNUMS[J] + nums[j + 1]-tmp < ABS (ANS-target): -Ans = nums[i] + nums[j] + nums[j + 1] - Break -Tmpans = Nums[i] + nums[j] +Nums[k] - ifTmpans-target < abs (ANS-target): -Ans =Tmpans inK-= 1 - Else: to ifNUMS[K] + nums[k-1] <=tmp: + ifTMP-NUMS[K]-nums[k-1] < abs (ANS-target): -Ans = nums[i] + nums[k-1] +Nums[k] the Break *Tmpans = Nums[i] + nums[j] +Nums[k] $ ifTarget-tmpans < abs (ANS-target):Panax NotoginsengAns =Tmpans -J + = 1 thei + = 1 + ifAns = =Target: A returnTarget the returnAns
View Code
Reprint Please specify source: http://www.cnblogs.com/chruny/p/4830175.html
[Leetcode] (python): 016-3sum Closest