听峰问雨 听峰问雨
首页
导航站
  • 编程语言

    • Python
  • 数据结构与算法
  • 设计模式
  • UVA
  • LeetCode
  • 《Go语言实战》
  • 《Go Web编程》
  • 《算法精粹 经典计算机科学问题的Python实现》
  • 学习
  • 博客搭建
  • 本站

    • 分类
    • 标签
    • 归档
  • 我的

    • 收藏
    • 关于
GitHub (opens new window)

zfprotectors

默默学习er
首页
导航站
  • 编程语言

    • Python
  • 数据结构与算法
  • 设计模式
  • UVA
  • LeetCode
  • 《Go语言实战》
  • 《Go Web编程》
  • 《算法精粹 经典计算机科学问题的Python实现》
  • 学习
  • 博客搭建
  • 本站

    • 分类
    • 标签
    • 归档
  • 我的

    • 收藏
    • 关于
GitHub (opens new window)
  • UVA

  • LeetCode

    • LeetCode1 - 两数之和
      • 问题
      • 题解
        • 方法一:暴力枚举
        • 方法二:哈希表
      • 代码
    • LeetCode53 - 最大子数组和
    • LeetCode88 - 合并两个有序数组
    • LeetCode217 - 存在重复元素
    • LeetCode1108 - IP地址无效化
    • LeetCode1290 - 二进制链表转整数
    • LeetCode1603 - 设计停车系统
  • ACM
  • LeetCode
zfprotectors
2022-06-22
目录

LeetCode1 - 两数之和

# 问题

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

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

示例 1:

输入:nums = [2,7,11,15], target = 9

输出:[0,1]

解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

# 题解

# 方法一:暴力枚举

遍历每个数x,寻找数组中是否存在target-x

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        n = len(nums)
        for i in range(n):
            for j in range(i+1, n):
                if nums[i] + nums[j] == target:
                    return [i,j]
        return []
1
2
3
4
5
6
7
8

时间复杂度:O(n^3)

空间复杂度:O(1)

# 方法二:哈希表

我们创建一个哈希表,遍历每个数x,并查询哈希表是否存在 target-x。

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        mp = {str(num):i for i,num in enumerate(nums)}

        for i in range(len(nums)):
            if str(target-nums[i]) in mp and i != int(mp[str(target-nums[i])]):
                return [i, int(mp[str(target-nums[i])])]
        return []
1
2
3
4
5
6
7
8

时间复杂度:O(n)

空间复杂度:O(n)

# 代码

创建一个哈希表,对于每一个 x,我们首先查询哈希表中是否存在 target - x,然后将 x 插入到哈希表中,即可保证不会让 x 和自己匹配。

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        mp = dict()
        for i,num in enumerate(nums):
            if target-num in mp:
                return [mp[target-num], i]
            mp[nums[i]]=i
        return []
1
2
3
4
5
6
7
8
编辑 (opens new window)
#数组#哈希表
UVA10878 - Decode the tape
LeetCode53 - 最大子数组和

← UVA10878 - Decode the tape LeetCode53 - 最大子数组和→

最近更新
01
LeetCode88 - 合并两个有序数组
06-22
02
LeetCode1603 - 设计停车系统
06-21
03
LeetCode53 - 最大子数组和
06-21
更多文章>
Theme by Vdoing | Copyright © 2021-2022 zfprotectors | 闽ICP备2021014222号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式