LeetCode 刷题记录——1. 两数之和

题目:

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

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

参考解答:

(参考链接:)

1.求差值;把差值存进字典里作为键;索引作为值;用列表长度作为索引。

时间复杂度:O(1) ,空间复杂度O(n) (补充:dict对象的存储结构采用的是散列表(hash表),其在最优情况下查询复杂度为O(1)

耗时:132 ms耗存:   13.1 MB                                                              

第一次循环理解:d[7]=0 即字典d={7:0},表示为索引0需要数组里值为7的元素配对。 if 判断是否为前面元素所需要配对的值 , 是则返回两个索引值。(补充:nums[x] in d  是判断值是否在字典某个key里面) 

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """           
        n = len(nums)
        #创建一个空字典
        d = {}
        for x in range(n):
            a = target - nums[x]
            #字典d中存在nums[x]时
            if nums[x] in d:
                return d[nums[x]],x
            #否则往字典增加键/值对
            else:
                d[a] = x
        #边往字典增加键/值对,边与nums[x]进行对比

2.求差值;把差值存进字典里作为键;索引作为值;用enumerate()做索引序列(也是由0开始)。做到了以空间换时间。

这里的  if tmp in d:最优情况下查询复杂度为O(1))。 不是if b in nums 时间复杂度是O(n) 这就是字典和list的区别

耗时:84 ms耗存:   13 MB                                                              
class Solution:
def twoSum(self, nums, target):
        """
        :typenums: List[int]
        :typetarget: int
        :rtype: List[int]
        """
        d = {}
        for i, vin enumerate(nums):
             m = target - v
            if d.get(m)is not None:
                 return [d[m], i]
            else:
                 d[v] = i

类似还有
class Solution:
def twoSum(self, nums, target):
        """
        :typenums: List[int]
        :typetarget: int
        :rtype: List[int]
        """
        d = {}
       if not nums:
           return None

       d = dict()
       for i, item in enumerate(nums):
           print('i,item',i,item)
           tmp = target - item
           if tmp in d:           #第一次循环为是空
               return [i, d[tmp]]
           d[item] = i    # 先把target_a及其所在的索引加入字典,找tmp若在字典里,那返回索引和字典键值对

       return None

2.求差值,判断差值是否在nums数组里。

时间复杂度:O(n^2),空间复杂度:O(1)   (补充:python中list对象的存储结构采用的是线性表,因此其查询复杂度为O(n) 也就是 if b in nums 时间复杂度是O(n)

耗时:976 ms耗存:  12.6 MB                                                                  
class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """       
        n = len(nums)
        for x in range(n):
            b = target-nums[x]
            if b in nums:
                y = nums.index(b)
                if y!=x:                 #防止自己位置上的4+4
                    return [x,y]

3.暴力循环:算法时间复杂度为O(n^2),空间复杂度:O(1)。

耗时:6180 ms耗存:   12.6MB                                                              
class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """        
        # 用len()方法取得nums列表的长度
        n = len(nums)
        # x取值从0一直到n(不包括n)
        for x in range(n):           
            #y取值从x+1一直到n(不包括n)
            #用x+1是减少不必要的循环,y的取值肯定是比x大        
            for y in range(x+1,n):
                #假如 target-nums[x]的某个值存在于nums中
                if nums[y] == target - nums[x]:
                    #返回x和y
                    return x,y

总结:

    1.要注意复杂度的问题,学着分析。

1)dict对象的存储结构采用的是散列表(hash表),其在最优情况下查询复杂度为O(1)

2)python中list对象的存储结构采用的是线性表,因此其查询复杂度为O(n) 也就是 if b in nums 时间复杂度是O(n)

    2.python用法

1) for i, vin enumerate(nums):   i为由0开始的索引,vin为相应的值
2) d.get(m)             在字典d里,查找m键
3) nums.index(b)   在nums列表里,查找元素b的索引

    3.转换为 target-nums[x]

    4.我好菜啊。

Python 字典(Dictionary) get() 函数返回指定键的值,如果值不在字典中返回默认值。

注:

get()方法语法: dict.get(key, default=None)

参数

  • key -- 字典中要查找的键。
  • default -- 如果指定键的值不存在时,返回该默认值值。

我新写了一个:

但复杂度还是高,忘记这句python中list对象的存储结构采用的是线性表,因此其查询复杂度为O(n) 也就是if target_a in nums 时间复杂度是O(n),那加上for循环,虽然代码看似很短,其实复杂度为o(n^2)

if tmp in 字典:最优情况下查询复杂度为O(1))。

968 ms12.5 MB
class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i, item in enumerate(nums):
            target_a = target - item
            if target_a in nums and nums.index(target_a) != i:
                return [i, nums.index(target_a)]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值
>