python 两数之和

版权声明:知识用于传播,才是真谛,欢迎转载,注明出处就好。 https://blog.csdn.net/GhostintheCode/article/details/84747946

两数之和 python实现

解法1

不用说耗时长,复杂度 O ( n 2 ) 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

猜你喜欢

转载自blog.csdn.net/GhostintheCode/article/details/84747946