Today begin formal title LeetCode brush journey, its own programming algorithm capabilities are bad, so I decided to carry on training hard, and a solution found in the code, optimization, and personal understanding, that's all.
Column - [LeetCode]
LeetCode subject classification summary
Given an array comprising n integers and a target nums target. Nums identify the three integers, and a target such that their closest. The three numbers and return.
Note: there is only assume that each group enter the only answer.
例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
Problem solution 1:
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
minval = 100000
nums.sort()
for i in range(len(nums)):
left = i + 1
right = len(nums) - 1
while left < right:
val = nums[i] + nums[left] + nums[right]
if abs(val - target) < minval:
minval = abs(val - target)
result = val
if val == target:
return target
if val <= target:
left += 1
else:
right -= 1
return result
Problem solution 2:
We think that the problem-solving approach double pointer, build l
and r
two pointers, then traverse nums
.
class Solution:
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
result = list()
nums.sort()
for i,m in enumerate(nums[0:-2]):
l, r = i + 1, len(nums) - 1
if nums[l] + nums[l + 1] + m > target:
result.append(nums[l] + nums[l + 1] + m)
elif nums[r] + nums[r - 1] + m < target:
result.append(nums[r] + nums[r - 1] + m)
else:
while l < r:
result.append(nums[l] + nums[r] + m)
if nums[l] + nums[r] + m < target:
l += 1
elif nums[l] + nums[r] + m > target:
r -= 1
else:
return target
result.sort(key=lambda x:abs(x-target))
return result[0]
We first nums
sort, then traverse nums
each element m
.
Sort greatly improved efficiency.
We determine nums
the maximum number of two plus m
post is not less than target
, if so, at this time we have no way to find and greater than three, and we need to build a result
array, and join them. We judge nums
the smallest two numbers plus m
post is not greater than target
, if so, at this time we have no way to find three smaller than this and, we must join them and to result
the.
After sorting by the minimum and maximum values and determines whether there is
target
the same situation, if there is, joined toresult
, and then to select.
This is the above-described two-step operation pruning operation.
Then for other cases, we then follow before the idea can be processed directly and join result
in, but there is no separate treatment for the minimum distance. Finally, and as long as we take target
the most recent value to (this policy to the sort
function).
By the absolute value of the size
result
sorting, you can select the smallest is the final result.
As it can be seen by the results of several experiments in the best possible 48ms, more than 99.8% of the people.