美文网首页LeetCode
python 两数之和

python 两数之和

作者: GhostintheCode | 来源:发表于2018-12-06 11:46 被阅读2次

两数之和 python实现

解法1

不用说耗时长,复杂度O(n^2)

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        n  = len(nums)
        for i in range(n):
            for j in range(i+1,n):
                if nums[j] == target - nums[i]:
                    return [i,j]

解法2

由于数组.index函数复杂度为O(1),整体复杂度降为O(n)看起来而已,其中target - nums[i] in nums 操作复杂度为O(n)

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        n  = len(nums)
        for i in range(n):
            if target - nums[i] in nums:
                y = nums.index(target - nums[i])
                if  i != y:
                    return [i,y]

解法3

通过空间换时间的思想,建立字典(内部实现为hash map)查找速度O(1)。
空间复杂度为O(n)

TODO 不是那么清楚为什么解法3比解法2快那么多,个人认为:

python中list对象的存储结构采用的是线性表,因此其查询复杂度为O(n),而dict对象的存储结构采用的是散列表(hash表),其在最优情况下查询复杂度为O(1)。

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        d = {}
        for x in range(len(nums)):
            rest = target - nums[x]
            #字典d中存在nums[x]时,就代表rest找到了,返回rest的下标,再根据字典找到rest的另一半的下标
            if nums[x] in d:
                return d[nums[x]],x
            #否则往字典增加键/值对,值是nums[x]的索引,
            else:
                d[rest] = x

相关文章

  • python 两数之和

    两数之和 python实现 解法1 不用说耗时长,复杂度 解法2 由于数组.index函数复杂度为O(1),整体复...

  • 两数之和 python

    执行用时为 28 ms 的范例 执行用时为 24 ms 的范例 执行用时为 20 ms 的范例

  • leetcode - python - 两数之和

    给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样的元素不能被...

  • leetcode两数之和—python

    一、暴力穷举 for i,num in enumerate(nums): for j,num2 in enume...

  • Python-两数之和

    给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的...

  • Python - LeetCode - 两数之和

    描述: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返...

  • Python版两数之和

    Given an array of integers, returnindicesof the two numbe...

  • (python实现)两数之和

    问题描述 给出一个整型数组 和一个目标值,请在数组中找出两个加起来等于目标值的数的下标,返回的下标按升序排列。数据...

  • Python小白 Leetcode刷题历程 No.1-No

    Python小白 Leetcode刷题历程 No.1-No.5 两数之和、两数相加、无重复字符的最长子...

  • 解决两数之和 (Javascript, Java, C#, Sw

    解决两数之和(Javascript, Java, C#, Swift, Kotlin, Python,C++,Go...

网友评论

    本文标题:python 两数之和

    本文链接:https://www.haomeiwen.com/subject/omgncqtx.html