Leetcode-三数之和

暴力解法:

class Solution:
    def threeSum(self, nums):
    	temp = {}
    	res = []
    	print(nums)
    	t_set = []
    	for i, num in enumerate(nums[:-2]):
    		for j_num in nums[i+1:]:
    			if j_num in temp:
    				for item in temp[j_num]:
    					item.append(j_num)
    					#item = set(item)
    					if set(item) in t_set:
    						continue
    					else:
    						t_set.append(set(item))
    					if item not in res:
    						res.append(item) 
    				temp.pop(j_num)
    				#break
    			target = 0-(num+j_num)
    			if target in temp:
    				temp[target].append([num, j_num])
    			else:
    				temp[target] = [[num, j_num]]
    			print(temp)
    		temp = {}
    	#res = [list(i) for i in res]
    	return res

双指针解法:
先对数列进行排序,这里选择递归排序,时间效率为nlogn,然后使用双指针进行三数之和是否为零判断

class Solution:
	def merge_sort(self, L):
		if len(L) <= 1:
			return L
		mid = len(L)//2 
		L_left = self.merge_sort(L[:mid])
		L_right = self.merge_sort(L[mid:])
		return self.merge(L_left, L_right)

	def merge(self, left, right):
		l = 0
		r = 0
		res = []
		while  l< len(left) and r < len(right):
			if left[l] < right[r]:
				res.append(left[l])
				l += 1
			else:
				res.append(right[r])
				r += 1
		res += left[l:]
		res += right[r:]
		return res

	def threeSum(self, nums):
		nums = self.merge_sort(nums)
		print(nums)
		n = len(nums)
		res = []
		for i in range(n):
			L = i + 1
			R = n - 1
			if nums[i] > 0:
				return res
			if i>0 and nums[i] == nums[i-1]:
				continue
			while L < R:
				if nums[i] + nums[L] + nums[R] == 0:
					print(i, L, R)
					res.append([nums[i], nums[L], nums[R]])
					while L< R and nums[L] == nums[L+1]:
						L += 1
					while L< R and nums[R] == nums[R-1]:
						R -= 1
					L += 1
					R -= 1
				elif nums[i] + nums[L] + nums[R] < 0:
					L += 1
				else:
					R -= 1
		return res
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值