leetcode 15. 三数之和 (python)

思路:
1先排序
2.外层遍历,i
3.内层用一个双指针判断,是否和为i
'''

参考博文

https://www.jianshu.com/p/588caa7567c1

https://www.jianshu.com/p/19b0261c73b9

#!/usr/bin/env python
# -*- coding:utf-8 -*- 
# Author: Jia ShiLin
'''
思路:
1先排序
2.外层遍历,i
3.内层用一个双指针判断,是否和为i
'''

def threeSum(nums):
    nums.sort()
    r = []
    for i in range(len(nums) - 2):
        left = i + 1
        right = len(nums) - 1

        if i > 0 and nums[i] == nums[i - 1]:  # 相同的数值只计算一次
            continue

        while left < right:
            three_sum = nums[i] + nums[left] + nums[right]
            if three_sum == 0:
                r.append([nums[i], nums[left], nums[right]])
                left += 1
                right -= 1
                while left < right and nums[left] == nums[left - 1]:
                    left += 1
                while left < right and nums[right] == nums[right + 1]:
                    right -= 1
            elif three_sum < 0:
                left += 1
            else:
                right -= 1
    return r


if __name__ == '__main__':
    print(threeSum([-1, 0, 1, 2, -1, -4]))

猜你喜欢

转载自blog.csdn.net/qq_35290785/article/details/88950070