leetcodeday5

And the number of the nearest three
1, similar to the previous, first sort, after traversing the double pointer
2, a variable setting for the number of the nearest village

class Solution(object):    
	def threeSumClosest(self, nums, target):
	"""        
	:type nums: List[int]        
	:type target: int        
	:rtype: int        
	"""
	nums.sort()  # 排序         
	i = 0        
	j = i + 1        
	t = len(nums)        
	k = t - 1        
	c = nums[i] + nums[j] + nums[k]  # 存储最接近的值
	while i < t - 2:
		# 双指针遍历            
		while j < k:
			if nums[i] + nums[j] + nums[k] == target:
				return target
			elif nums[i] + nums[j] + nums[k] > target:
				if abs(c - target) >  abs(nums[i] + nums[j] + nums[k] - target): 
					c = nums[i] + nums[j] + nums[k]
				k -= 1
				while k < j and nums[k] == nums[k + 1]:  # 跳过重复值
					k -= 1
			else:
				if abs(c - target) >  abs(nums[i] + nums[j] + nums[k] - target):
					c = nums[i] + nums[j] + nums[k]
				j += 1
				while j < k and nums[j] == nums[j - 1]:
					j += 1
		i += 1
		while i < t - 2 and nums[i] == nums[i - 1]:
			i += 1
		j = i + 1
		k = t - 1
	return c


					
Released five original articles · won praise 0 · Views 26

Guess you like

Origin blog.csdn.net/weixin_45737540/article/details/104682525