[LeetCode] 15. 3Sum 三数之和 @python
2018-03-18 13:58
501 查看
Description
Given an array S of n integers, are there elements a, b, c in S 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. For example, given array S = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
给定一个包含 n 个整数的数组 S,是否存在属于 S 的三个元素 a,b,c 使得 a + b + c = 0 ?找出所有不重复的三个元素组合使三个数的和为零。
注意:结果不能包括重复的三个数的组合。 例如, 给定数组 S = [-1, 0, 1, 2, -1, -4], 一个结果集合为: [ [-1, 0, 1], [-1, -1, 2] ]
Solutions
需要求的就是a+b=(-c),然后在余下的链表里做两数相加即可。注意去重!
# -*- coding: utf-8 -*- """ Created on Sat Mar 17 16:30:25 2018 @author: Saul """ class Solution: def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ ans = [] nums.sort() for i in range(len(nums)-2): if i == 0 or nums[i] > nums[i-1]: left = i+1 right = len(nums)-1 while left < right: ident = nums[left] + nums[right] + nums[i] if ident == 0: ans.append([nums[i], nums[left], nums[right]]) left += 1; right -= 1 while left < right and nums[left] == nums[left-1]: # skip duplicates left += 1 while left < right and nums[right] == nums[right+1]: right -= 1 elif ident < 0: left += 1 else: right -= 1 return ans
相关文章推荐
- [LeetCode] 15. 3Sum 三数之和
- Leetcode #15 3Sum 三数之和 解题小节
- Leetcode: 15. 3Sum 三数之和
- 【Leetcode 15】3Sum 三数和问题 C++
- LeetCode | 15. 3Sum(三数和为定值)
- [LeetCode] 15. 3Sum
- 【一天一道LeetCode】#15 3Sum
- leetcode15 3Sum
- Leetcode - 15. 3Sum
- [leetcode] 15. 3Sum
- 【LeetCode 15】3Sum (C++)
- 3Sum (leetcode 15)
- LeetCode(15) 3Sum
- LeetCode 15 3Sum
- leetcode15---3Sum
- LeetCode15:3Sum
- LeetCode15:3Sum
- [Leetcode] 15. 3Sum 解题报告
- leetCode_15_3Sum
- leetcode 15 3Sum