首页 > 编程语言 > 详细

leetcode 3Sum python

时间:2015-11-19 23:55:08      阅读:359      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!