[Leetcode.python] 001. Two Sum


在学习新语言Python, 决定使用Python刷刷Leetcode.


  • 题目001:Two Sum (https://leetcode.com/problems/two-sum/)

大意,给定一个数组nums和一个数target,确定有且只有一对坐标index1, index2, 使得nums[index1] + nums[index2] == target

  • 解答:
    • 最直接的方法,穷举 O(N^2),提交后会超时
    def twoSum(self, nums, target):
        length = len(nums)
        answers = []
        for index1 in range(0, length - 2):
            for index2 in range(index1 + 1, length - 1):
                if nums[index1] + nums[index2] == target:
                    answers.append(index1 + 1)
                    answers.append(index2 + 1)
        return answers

    • 可以修改为先排序,时间复杂度O(N*logN)
    def twoSum(self, nums, target):
        sorted_nums = sorted(nums, cmp=lambda x,y:cmp(x, y))

        length = len(nums)
        index1 = 0
        index2 = length - 1
        while index1 < index2:
            gap = sorted_nums[index1] + sorted_nums[index2] - target
            if gap == 0:
                break
            elif gap < 0:
                index1 += 1
            else:
                index2 -= 1

        answers = []
        for index in range(0, length):
            if (nums[index] == sorted_nums[index1]) or (nums[index] == sorted_nums[index2]):
                answers.append(index + 1)
        return answers
    • 使用Hash/Set,可以进一步降低时间复杂度为O(N)
    def twoSum(self, nums, target):
        num_set = set(nums)

        answers = []
        # a. nums[index1] != nums[index2]
        for index1 in range(0, len(nums)):
            number_to_be_found = target - nums[index1]
            if number_to_be_found != nums[index1] and number_to_be_found in num_set:
                answers.append(index1 + 1)
                for index2 in range(index1 + 1, len(nums)):
                    if nums[index2] == number_to_be_found:
                        answers.append(index2 + 1)
                        break
                break

        # b. nums[index1] == nums[index2]
        if answers == []:
            number_to_be_found = target / 2
            if (number_to_be_found + number_to_be_found == target):
                for index in range(0, len(nums)):
                    if nums[index] == number_to_be_found:
                        answers.append(index + 1)
        return answers

  • 注意事项
    • 数组不确定为有序
    • 可能存在重复的元素


欢迎大家关注我的微信公众号 - “水滴杂谈”

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值