第一天:在LeetCode上写的每日一道题

博主是一名在校统计专业大学生,写这个系列是为了记录学习python过程中的题目,希望对自己未来计算机的学习有帮助,目前刚开始学习,在力扣上只会做简单类型的题目= =

两数之和

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

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

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

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

方法一:列表遍历循环法

这个方法是最容易想到的,也是一开始我做的,但是时间很长,时间复杂度高,因为有两个for循环

class Solution:
    def twoSum(self, nums: List[int], target: int) -> 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]
        return []  

方法二:字典查找,很惊艳,之前在课上用二分法时的题目也可以用,但是不知道为什么比二分法慢,可能是因为这个要查找全部的而二分法不用

def twoSum(nums, target):
    hashmap={}
    for ind,num in enumerate(nums):
        hashmap[num] = ind
    for i,num in enumerate(nums):
        j = hashmap.get(target - num)
        if j is not None and i!=j:
            return [i,j]  

方法三:字典,在第一个数之前的字典中查找即可

def twoSum(nums, target):
    hashmap={}
    for i,num in enumerate(nums):
        if hashmap.get(target - num) is not None:
            return [i,hashmap.get(target - num)]
        hashmap[num] = i #这句不能放在if语句之前,解决list中有重复值或target-num=num的情况

方法四:遍历的同时创建字典,我认为是最好的一种

def two_sum(nums, target):
    """这样写更直观,遍历列表同时查字典"""
    dct = {}
    for i, n in enumerate(nums):
        cp = target - n
        if cp in dct:
            return [dct[cp], i]
        else:
            dct[n] = i

  方法五:在列表中,但是从第一个数字之前或之后循环,并且是通过寻找target-num的方式,而并不是像第一个一样两个加起来

def twoSum(nums, target):
    lens = len(nums)
    j=-1
    for i in range(1,lens):
        temp = nums[:i]
        if (target - nums[i]) in temp:
            j = temp.index(target - nums[i])
            break
    if j>=0:
        return [j,i]
posted @ 2020-12-27 20:55  仙子qwq  Views(87)  Comments(2)    收藏  举报