码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode 3Sum python

时间:2015-11-19 23:56:50      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:

# sort the array
# loop from i = 0
# then left=i+1 right=len(nums)-1
# try nums[i] - ( nums[left]+nums[right]) = 0
#


class
Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ res=list() nums.sort() if len(nums) <= 2: return res for index in range(len(nums)-2): if index == 0 or nums[index] > nums[index-1]: left=index+1 right=len(nums)-1 while left < right: if nums[left] + nums[right] == -nums[index]: res.append( [nums[index],nums[left],nums[right] ] ) left+=1 right-=1
              #ensure no repeat value while left<right and nums[left] == nums[left-1]: left+=1 while left < right and nums[right] == nums[right+1]: right-=1 elif nums[left] + nums[right] < -nums[index]: while left < right: left+=1 if nums[left] != nums[left-1]: break else: while left < right: right-=1 if nums[right] != nums[right+1]: break return res

@link http://www.cnblogs.com/zuoyuan/p/3699159.html

leetcode 3Sum python

标签:

原文地址:http://www.cnblogs.com/allenhaozi/p/4979427.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!