leetcode 腾讯精选练习(50 题)15.三数之和
2019-05-18 20:45
671 查看
原题目
Given an array
numsof n integers, are there elements a, b, cinnumssuch 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
自己可以改进的地方
最简代码
获得的思考
相关文章推荐
- leetcode NO.2两数相加 腾讯精选练习50
- leetcode NO.7 整数反转 腾讯精选练习50
- leetcode 腾讯精选练习(50 题)16.最接近的三数之和
- leetcode 腾讯精选练习(50 题)43.字符串相乘
- leetcode 腾讯精选练习(50 题)26.删除排序数组中的重复项
- leetcode 腾讯精选练习(50 题)33.搜索旋转排序数组
- leetcode腾讯精选50-008
- leetcode腾讯精选50-016
- leetcode腾讯精选50-015
- leetcode 腾讯精选50
- leetcode腾讯精选50-003
- leetcode腾讯精选50-021
- Leetcode腾讯精选_编号:9 --python
- Leetcode腾讯精选_编号:46 --python
- Leetcode腾讯精选_编号:121 --python
- Leetcode腾讯精选_编号:230 --java
- Leetcode练习-Roman to Integer"M": 1000, "D": 500, "C": 100, "L": 50, "X": 10, "V": 5, "I": 1
- Leetcode腾讯精选_编号:11 --python
- Leetcode腾讯精选_编号:53 --python
- Leetcode腾讯精选_编号:136 --python