当前位置:   article > 正文

LeetCode刷题笔记——1. 两数之和_py给定两个以升序排列的整形数组 nums1 和 nums2 以及一个整数 k。 定义一对值 (

py给定两个以升序排列的整形数组 nums1 和 nums2 以及一个整数 k。 定义一对值 (

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

题目

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

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

示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

利用两个循环解决

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]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

结果:
在这里插入图片描述

改进方法

利用python的字典来解决问题
首先,遍历列表,将列表中的第一个添加到字典当中。
在之后的列表中,每遍历一个节点,就在字典中寻找是否存在与其相加的和等于目标值的数,若存在则返回这两个数在列表中的位置,否则将该节点加入列表中并继续遍历下一个节点。

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hashmap = {}
        for index, num in enumerate(nums):
            another_num = target - num
            if another_num in hashmap:
                return [hashmap[another_num], index]
            hashmap[num] = index
        return None
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

在这里插入图片描述
很明显,时间复杂度降低了。

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号