LintCode_chapter2_section8_three-sum

coding = utf-8

'''
Created on 2015年11月9日

@author: SphinxW
'''
# 三数之和
#
# 给出一个有n个整数的数组S,在S中找到三个整数a, b, c,找到所有使得a + b + c = 0的三元组。
# 您在真实的面试中是否遇到过这个题?
# 样例
#
# 如S = {-1 0 1 2 -1 -4}, 你需要返回的三元组集合的是:
#
# (-1, 0, 1)
#
# (-1, -1, 2)
# 注意
#
# 在三元组(a, b, c),要求a <= b <= c。
#
# 结果不能包含重复的三元组。


class Solution:
    """
    @param numbersbers : Give an array numbersbers of n integer
    @return : Find all unique triplets in the array which gives the sum of zero.
    """

    def threeSum(self, numbers):
        # write your code here
        numbers.sort()
        res = []
        fsum = numbers[0] + numbers[1] + numbers[2]
        for index in range(len(numbers)):
            headIndex = 0
            tailIndex = len(numbers) - 1
            while headIndex < tailIndex:
                if headIndex >= index:
                    break
                if tailIndex <= index:
                    break
                sum = numbers[headIndex] + numbers[index] + numbers[tailIndex]
                if sum == 0:
                    res.append(
                        (numbers[headIndex], numbers[index], numbers[tailIndex]))
                    headIndex += 1
                if sum > 0:
                    tailIndex -= 1
                if sum < 0:
                    headIndex += 1
        res = list(set(res))
        return res
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 可以看我的博客 lmwen.top 或者订阅我的公众号 简介有稍微接触python的人就会知道,python中...
    ayuLiao阅读 3,266评论 1 5
  • 字符集和编码简介 在编程中常常可以见到各种字符集和编码,包括ASCII,MBCS,Unicode等字符集。确切的说...
    兰山小亭阅读 8,785评论 0 13
  • 1、开启公众号开发者模式 公众平台的技术文档目的为了简明扼要的交代接口的使用,语句难免苦涩难懂,甚至对于不同的读者...
    good7758阅读 1,578评论 0 1
  • python 中的unicode是让人很困惑、比较难以理解的问题.这篇文章写的比较好,utf-8是 unicode...
    think_lonely阅读 938评论 0 0
  • 每隔几年,我都要重写一遍“老屋”这个题材,老屋是我爷爷奶奶的家。按说,我应该对临浦戴家桥头的家更有感情才对,但这么...
    慢尘行阅读 380评论 7 4