您的位置:首页 > 其它

leetcode 腾讯精选练习(50 题)15.三数之和

2019-05-18 20:45 671 查看

原题目

Given an array

nums
of n integers, are there elements a, b, cin
nums
such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],A solution set is:[[-1, 0, 1],[-1, -1, 2]]

思路

第一遍解法

网上好的解法

# 首先对列表从小到大排序# 从最小的开始遍历寻找三数之和为0的结果(len(nums)-2 是因为 low=i+1不能越界)# 剩下的两个数从 选定数的下一个 和 最后一个数 向中间收缩# 三数之和小于0应向变大方向移动,反之向小的方向移动# 关于跳过# 对于遍历的元素,后面和前面相等跳过,因为前面已经把符合的答案加入最终结果列表# 对于移动的两个元素,三数之和为0的时候同时向中间收缩,同时有相等值跳过# low < high 一直都是很重要的判断条件class Solution:def threeSum(self, nums):ans = []nums.sort()for i in range(len(nums)-2):if i > 0 and nums[i] == nums[i-1]:continuelow, high = i+1, len(nums)-1while low < high:sum_three = nums[i] + nums[low] + nums[high]if sum_three < 0:low += 1elif sum_three > 0:high -= 1else:ans.append([nums[i], nums[low], nums[high]])while low < high and  nums[low] == nums[low+1]:low += 1while low < high and nums[high] == nums[high-1]:high -= 1low += 1high -= 1return ans

自己可以改进的地方

最简代码

获得的思考

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: