LeetCode 1:two sum

1 Python刷

1.1 暴力法:时间O(n^2),空间O(1)

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

1.2 一个for循环:时间O(n^2),空间O(1)

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)):
            diff = target - nums[i] 
            if diff in nums: # 判断差的数在不在列表里
                idx = nums.index(diff)
                if idx != i:# 但是不能重复索引数字
                    return[i,idx]
                    break

1.3 不必每次搜索全部列表,搜索剩余列表即可:时间O(n^2),空间O(1)

https://leetcode-cn.com/problems/two-sum/solution/xiao-bai-pythonji-chong-jie-fa-by-lao-la-rou-yue-j/

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)):
            diff = target - nums[i] 
            temp = nums[i+1:]
            if diff in temp: # 判断差的数在不在剩余列表里
                idx = temp.index(diff)
                return[i,idx+i+1] # 记得idx是新列表中的索引,要还原到原列表
                break

1.4 两遍哈希:用字典模拟哈希表,通过字典去查询:时间O(n),空间O(n)

为了对运行时间复杂度进行优化,我们需要一种更有效的方法来检查数组中是否存在目标元素。如果存在,我们需要找出它的索引。保持数组中的每个元素与其索引相互对应的最好方法是什么?哈希表。https://leetcode-cn.com/problems/two-sum/solution/liang-shu-zhi-he-by-leetcode-2/

哈希表(散列表)是根据键(Key)直接访问内存存储位置的数据结构。根据键(Key)值将数据映射到内存中一个位置的函数称为哈希函数,根据哈希函数建立的记录数据的表称为哈希表。

通过以空间换取速度的方式,我们可以将查找时间从 O(n)降低到 O(1)。哈希表正是为此目的而构建的,它支持以近似恒定的时间O(1)进行快速查找。

一个简单的实现使用了两次迭代。在第一次迭代中,我们将每个元素的值和它的索引添加到表中。然后,在第二次迭代中,我们将检查每个元素所对应的目标元素是否存在于表中。注意,该目标元素不能是元素本身!

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        hashmap = {} # 用字典代替哈希表功能
        # 将每个元素的值和它的索引添加到哈希表
        for idx, num in enumerate(nums):
            # 注意这里是原来的数值存成key键值,原来的索引存成字典的值
            hashmap[num] = idx # 原列表中同一个数字num如果有重复出现,那么构建字典过程中会被后出现的覆盖
            # 但是前面for循环中idx和num还是分别对应原始列表的索引和数值
            '''e.g.1
            nums = [2, 2, 4, 6] target=4
            {2: 0}
            {2: 1}
            {2: 1, 4: 2}
            {2: 1, 4: 2, 6: 3}
            e.g.2
            nums = [2, 1, 4, 6, 2]
            {2: 0}
            {2: 0, 1: 1}
            {2: 0, 1: 1, 4: 2}
            {2: 0, 1: 1, 4: 2, 6: 3}
            {2: 4, 1: 1, 4: 2, 6: 3}
            '''
        for idx, num in enumerate(nums):
            j = hashmap.get(target - num) #Python字典get()函数返回指定键的值,对于重复数字,一定是后一个的索引
            if j is not None and j != idx:# 注意这里,用原始列表的索引比较,就是重复数字的第一个的索引
                return [idx, j]

1.5 一遍哈希:时间O(n),空间O(n)

在进行迭代并将元素插入到表中的同时,我们还会回过头来检查表中是否已经存在当前元素所对应的目标元素。如果它存在,那我们已经找到了对应解,并立即将其返回。

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        hashmap = {} # 用字典代替哈希表功能
        for idx, num in enumerate(nums):
            if hashmap.get(target - num) is not None:
                return [hashmap.get(target - num), idx]# 如果哈希表中已经有过可以找到差值对应的,那么一定是更靠前的,所以idx在后
                break
            hashmap[num] = idx # 第一遍hashmap为空,故找不到跟第一个元素配对的数值,把第一元素加入字典
            # 之后每次找不到对应的差的值才把它加入哈希表

  

2 用Python3刷

函数的输入和输出变量类型注解参考:https://zhuanlan.zhihu.com/p/37239021

class Solution:
    #def twoSum(self, nums: List[int], target: int) -> List[int]:    
    def twoSum(self, nums, target):
        hashmap = {} # 用字典代替哈希表功能
        '''
        for idx, num in enumerate(nums):
            if num in hashmap:
                return [hashmap[num], idx] # 如果哈希表中已经有过对应差值,那么一定是更靠前的,所以idx在后
                break
            hashmap[target - num] = idx # 差值的哈希表,每次都是搜索差值是不是已经在哈希表中,如果在说明之前遍历过了  
            # 1 3 2 7     target = 5
            # 4 2 √
        '''
        for idx, num in enumerate(nums):
            if target - num in hashmap:
                return [hashmap[target - num], idx]
                break
            hashmap[num] = idx # 原始数值的哈希表
            # 1 3 2 7     target = 5
            # 1 3 √
        
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值