Skip to content

minor changes but made the code run 33% faster #37

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 23 additions & 5 deletions Array/ThreeSum/ThreeSum.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,36 @@
# O(n * n)
class Solution(object):
def threeSum(self, nums):
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
nums.sort() # 排序
for i in xrange(0, len(nums) - 2):
nums.sort()
nums_len = len(nums)
# 去除例外,包括:小于三个元素的list,最小值大于0的,最大值小于0的
if nums_len < 3:
return []
if nums[0] > 0:
return []
if nums[-1] < 0:
return []

for i in range(0, nums_len - 2):
# 如果当前值大于0的话,跳出for循环,因为剩下的两个数肯定大于等于当前数
if nums[i] > 0:
break
# 如果前三个数相加大于0的话则跳出for循环,因为接下来的任何三个数相加都会超过0
if 0 < nums[i] + nums[i+1] + nums[i+2]:
break
# 如果当前数加上最大的两个数还小于0的话则说明当前数太小,不可能找到符合要求的组合,则跳过当前数。
if 0 > nums[i] + nums[-1] + nums[-2]:
continue
# 如果与前一个值相同,则跳过
# 避免重复计算
if i > 0 and nums[i] == nums[i-1]:
continue
l, r = i + 1, len(nums) - 1
l, r = i + 1, nums_len - 1
while l < r:
s = nums[i] + nums[l] + nums[r]
if s < 0:
Expand Down