leecode练习(一)两数之和

题目要求:

  • 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的 两个 整数。
  • 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

小白学python,基础的语法已懂,但不太会操作,所以补上所需知识点~

1. tuple
tuple是一种list,但与list有区别的是tuple不可变。因此,tuple也可以用切片操作,只是操作的结果仍是tuple。

(0,1,2,3,4,5)[:3]
(0, 1, 2)

2.列表生成式
列表生成式即List Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式。举个?,要生成list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]可以用list(range(1, 11)):

list(range(1,11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

作为一个萌新、小白、掉包小贼,接下来主要还是要学习算法啦o( ̄▽ ̄)o
大约有三种思路!

  • 解法一:求差值法
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):
            x = target - nums[i]
            if x in nums:
                y = nums.index(x)
                if y!=i:
                    return i,y

逃不开的循环,假定i在,那么target-i若在,取下标~

  • 解法二:直接循环
class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        n = len(nums)
        #x取值从0到n
        for x in range(n):
            #y取值从x+1到n
            for y in range(x+1,n):
                if nums[y] == target - nums[x]:
                    return x,y
  • 解法三:求差值,并使用字典求解
class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        n =len(nums)
        #创建一个空字典
        dict ={}
        for x in range(n):
            a = target - nums[x]
            #判断字典中是否存在nums[x],不存在向其中增加键值对
            if nums[x] in dict:
                return dict[nums[x]],x
            else:
                dict[a]=x  #修改x对应的值为a

▶分析三种算法的时间复杂度,空间复杂度:

算法分析解法时间复杂度空间复杂度
解法一O(n*2)O(1)
解法二O(n*2)O(1)
解法三O(1)O(n)
字典采用的存储结构是哈希表,以空间换时间
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值