鱼C论坛

 找回密码
 立即注册
查看: 860|回复: 3

题的问题

[复制链接]
发表于 2020-5-9 11:23:20 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
例子:给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
  1. class Solution:
  2.     def threeSum(self, nums: List[int]) -> List[List[int]]:
  3.         nums = sorted(nums)
  4.         if len(nums) < 3 or nums[0] > 0 or nums[-1] < 0:
  5.             return []
  6.         
  7.         result = []
  8.         i = 0

  9.         while nums[i] <= 0 and i < len(nums)-1:
  10.             if i > 0 and nums[i] == nums[i-1]:
  11.                 i += 1
  12.                 continue
  13.             j = i+1
  14.             k = len(nums)-1
  15.             while j<k:   
  16.                 if nums[j]+nums[i]+nums[k] > 0:
  17.                     k -= 1
  18.                     # while k > j and nums[k] == nums[k+1]:
  19.                     #     k -= 1
  20.                 elif nums[j]+nums[i]+nums[k] < 0:
  21.                     j += 1
  22.                     # while j < k and nums[j]==nums[j-1]:
  23.                     #     j += 1
  24.                 else:
  25.                     result.extend([[nums[i],nums[j],nums[k]]])
  26.                     j += 1
  27.                     k -= 1
  28.                     while j<k and nums[k] == nums[k+1]: k-=1
  29.                     while j<k and nums[j] == nums[j-1]: j+=1
  30.             i += 1
  31.         return result
复制代码

为什么注释的几行去掉后 效率提高了很多呢?
思路是固定最左边 然后右边双指针寻找 跳过重复项
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-5-9 14:04:06 | 显示全部楼层
你注释的部分就是跳过重复项的操作呀
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-5-9 14:09:15 | 显示全部楼层
combinations函数便方便些
  1. nums = [-1, 0, 1, 2, -1, -4]
  2. from itertools import combinations as cb
  3. def threeSum(nums):
  4.     result=[]
  5.     for i in cb(nums,3):
  6.         j=sorted(list(i))
  7.         if sum(j)==0 and j not in result:
  8.             result.append(j)
  9.     return result
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-5-9 14:55:20 | 显示全部楼层
不会
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-19 01:16

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表