当前位置: 代码迷 >> 综合 >> 每天一道leetecode:15、三数之和(medium)
  详细解决方案

每天一道leetecode:15、三数之和(medium)

热度:46   发布时间:2023-12-14 15:04:38.0

这道题一开始做的时候,感觉自己的时间也是卡在了n^2,顶多就是大一点点,哈哈哈

开始的代码如下:

def threeSum(nums):len_nums = len(nums)two_sum = list()# 先计算两个的加和for i in range(len_nums):for j in range(i+1,len_nums):two_sum.append(nums[i] + nums[j])print(nums)print(two_sum)len_two_sum = len(two_sum)for i in range(100):if i * (i+1) == 2 * len_two_sum:k = ibreaky = []for i in range(len_nums):for j in range(len_two_sum):if nums[i] + two_sum[j] == 0:column = 0p = kif j < p:a = 0b = j + 1else:m = jwhile m >= p:m -= pp -= 1column += 1a = columnb = m + column + 1no = 1if a == b or a == i or b == i:no = 0if no != 0:y.append([nums[a],nums[b],nums[i]])for data in y:data.sort()h = []for data in y:data = tuple(data)h.append(data)print(h)h = set(h)res = []for data in h:h = list(data)res.append(h)return resnums = list()
nums.append(-1)
nums.append(0)
nums.append(1)
nums.append(2)
nums.append(-1)
nums.append(-4)print(threeSum(nums))

先计算两个的加和,然后计算三个的加和,可是还是面临超时的问题。

然后今天静下心来,重新采用了一种思路写了一下:
 

然后,就通过了。。。

def threeSum(nums):# 先排序for i in range(len(nums)):for j in range(i + 1, len(nums)):if nums[i] > nums[j]:k = nums[i]nums[i] = nums[j]nums[j] = k#print(nums)# 然后设置三个指针y = []global k_k_ = 521l_ = 521r_ = 521for k in range(len(nums)):if nums[k] == k_:continueif nums[k] > 0:breakl = k + 1r = len(nums) - 1print('1l:',l,' r:',r)k_ = 521l_ = 521r_ = 521while l < r:if nums[l] == l_:l = l + 1print('2l:', l, ' r:', r)continueif nums[r] == r_:r = r - 1print('3l:', l, ' r:', r)continue# 如果满足条件if nums[k] + nums[l] + nums[r] == 0:y.append([nums[k], nums[l], nums[r]])l_ = nums[l]r_ = nums[r]l = l + 1r = r - 1print('4l:', l, ' r:', r)# 如果小于0,则左边指针+if nums[k] + nums[l] + nums[r] < 0:l_ = nums[l]l = l + 1print('5l:', l, ' r:', r)# 如果大于0,则右边指针-if nums[k] + nums[l] + nums[r] > 0:r_ = nums[r]r = r - 1print('6l:', l, ' r:', r)k_ = nums[k]print(k_)return ynums = list()
nums.append(-1)
nums.append(0)
nums.append(1)
nums.append(2)
nums.append(-1)
nums.append(-4)nums1 = list()
nums1.append(0)
nums1.append(0)
nums1.append(0)nums2 = list()
nums2.append(-2)
nums2.append(-1)
nums2.append(1)
nums2.append(0)
nums2.append(2)
nums2.append(3)
print(threeSum(nums2))

  相关解决方案