[Leetcode.python] 001. Two Sum

来源:互联网 发布:人工智能网站 编辑:程序博客网 时间:2024/05/18 00:13


在学习新语言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
原创粉丝点击