您的位置:首页 > 编程语言 > Python开发

[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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python leetcode