LeetCode_每天一题_python_ 第一题两数之和

python 每天写一个算法题

第一天

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum

1.暴力算法 

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in range(0, len(nums)):
            for j in range(i + 1, len(nums)):
                if nums[i] + nums[j] == target:
                    return [i, j]
        return[]

2.运用字典 模拟哈希求解

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hashmap = {}
        for ind, num in enumerate(nums):
            hashmap[num] = ind
            #   hashmap = {(2,0),(7,1),(11,2),(15,3)}
        for i, num in enumerate(nums):
             j = hashmap.get(target - num)
            #   j : 2 7 None None
             if j is not None and i != j:
                return [i, j]

猜你喜欢

转载自blog.csdn.net/qq_42548880/article/details/108355177
今日推荐