首页 > 其他 > 详细

leetcode------3Sum

时间:2015-04-08 19:38:16      阅读:92      评论:0      收藏:0      [点我收藏+]
标题: 3Sum
通过率:  16.9%
难度: 中等

Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • 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)

从本题开始用python做题;

前面做过一个2sum用的是map方法,这次用的是一个适合与Ksum的方面。基础依然是2sum

2sum用两个指针进行做,start指针指向开头,end指针指向结尾开始匹配,

对于3sum就是加一层循环,从第零个位置开始,进入到2sum时是从第一个开始

对于4sum就是在2sum外面加两层

一次类推

代码如下:

 1 class Solution:
 2     # @return a list of lists of length 3, [[val1,val2,val3]]
 3     def threeSum(self, num):
 4         num.sort()
 5         ans = []
 6         target=0
 7         for i in range(0, len(num)):
 8             l, r = i + 1, len(num) - 1
 9             while l < r:
10                 sum = num[i] + num[l] + num[r] 
11                 if sum == target:
12                     tmp=[num[i], num[l], num[r]]
13                     if tmp not in ans:
14                         ans.append(tmp)
15                     l, r = l + 1, r - 1
16                 elif sum < target:
17                     l = l + 1
18                 else:
19                     r = r - 1   
20         return ans

 

leetcode------3Sum

原文:http://www.cnblogs.com/pkuYang/p/4403413.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!