【Leetcode】数组题目【Python】

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dic={}  #dict = dict()
        for index,value in enumerate(nums):
            #enumerate将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
            sub = target-value
            if sub in dic:
                return [dic[sub],index]
            else:
                dic[value]=index

"""
先进行排序
J,k两端向内逼近,若三数相加为0,则append
去重:法一:利用result_list如果里面存在result,则不进行append,此方法(超时)
      法二:判断j右边与j,k与k左边是否值相等,相等则进行移动
当j!<k循环中止
"""
class Solution(object):
    def threeSum(self,nums):
        length = len(nums)
        result_list = []
        nums.sort()
        for i in range(length-2):
            j = i+1
            k = length-1
            while j<k:
                sum = nums[i]+nums[j]+nums[k]
                if sum==0:
                    result=[]
                    result.extend([nums[i],nums[j],nums[k]])
                    if result not in result_list: #此处时间复杂度较高
                        result_list.append(result)
                    j+=1
                    k-=1
                elif sum<0:
                    j+=1
                elif sum>0:
                    k-=1
        return result_list

    def threeSum1(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        ans = []
        nums.sort()
        for i in range(len(nums) - 2):
            if i == 0 or nums[i] > nums[i - 1]:
                left = i + 1
                right = len(nums) - 1
                while left < right:
                    ident = nums[left] + nums[right] + nums[i]
                    if ident == 0:
                        ans.append([nums[i], nums[left],nums[right]])
                        left += 1;
                        right -= 1
                        while left < right and nums[left] == nums[left - 1]:  # skip duplicates
                            left += 1
                        while left < right and nums[right] == nums[right + 1]:
                            right -= 1
                    elif ident < 0:
                        left += 1
                    else:
                        right -= 1
        return ans


a=Solution()
nums=[-1,0,1,2,-1,-4]
print(a.threeSum(nums))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值