zoukankan      html  css  js  c++  java
  • [算法题] 3Sum

    题目内容

    题目来源:LeetCode

    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]
    ]

    题目思路

    本题难度:medium

    本题是在2sum的基础上延伸的。在2sum中,target是一个函数的输入值。而在这里处理3sum的时候,使用一个循环遍历nums数组,分别让target= -(nums[i])。然后就可以将问题转换为2sum,只不过比2sum多了一个for循环。

    这个方法可以推广到一般的ksum的情况,ksum需要k-2次循环。

    这里使用的方法是在2sum中提到的双指针法。需要说明的是,在本题中,提到了结果不允许重复,因此在移动指针的时候,需要判断是否重复。

    Python代码

    class Solution(object):
        def threeSum(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            nums=sorted(nums)
            _len=len(nums)
            res=[]
            for i in xrange(_len-2):
                if nums[i]==nums[i-1] and i>0:
                    continue
                target=nums[i]
                left=i+1
                right=_len-1
                while left<right:
                    _sum=nums[left]+nums[right]
                    if _sum+target==0:
                        res.append([nums[i],nums[left],nums[right]])
                        while left<right and nums[left]==nums[left+1]:
                            left+=1
                        while left<right and nums[right]==nums[right-1]:
                            right-=1
                        left+=1
                        right-=1
                    elif _sum+target<0:
                        left+=1
                    elif _sum+target>0:
                        right-=1
            return res
    
    
  • 相关阅读:
    authentication与网站安全验证
    Android 不一样的原生分享
    iOS学习笔记——AutoLayout的约束
    积累一下SQL
    关于数据链接底层
    减少生成的dll数量
    iOS学习笔记——使用ChildViewController
    iOS学习笔记——键盘处理
    iOS学习笔记——触控与手势
    iOS学习笔记——多控制器管理
  • 原文地址:https://www.cnblogs.com/chengyuanqi/p/7125570.html
Copyright © 2011-2022 走看看