leetcode热题100.两数之和

简介: leetcode热题100.两数之和

题目

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个

整数,并返回它们的数组下标。

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

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

示例 1:

输入:nums = [2,7,11,15], target = 9 输出:[0,1] 解释:因为 nums[0] + nums[1] ==

9 ,返回 [0, 1] 。 示例 2:

输入:nums = [3,2,4], target = 6 输出:[1,2] 示例 3:

输入:nums = [3,3], target = 6 输出:[0,1]

提示:

2 <= nums.length <= 104

-109 <= nums[i] <= 109

-109 <= target <= 109 只会存在一个有效答案

进阶:你可以想出一个时间复杂度小于 O ( n 2 ) O(n^2)O(n2) 的算法吗?

思路1

两层循环遍历整个数组,如果他们的和为target则返回索引

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 1

思路2

创建一个字典,记录所有已经访问过的数字,遍历所有nums的值,如果当前 target - nums[i]

可以在字典中被找到,说明数组中存在两个数的和为target,返回这两个数即可

时间复杂度: n ( n ) n(n)n(n) 空间复杂度: n ( n ) n(n)n(n)

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


目录
相关文章
LeetCode 热题100——单调栈
LeetCode 热题100——单调栈
19 0
|
1月前
|
算法
LeetCode刷题---167. 两数之和 II - 输入有序数组(双指针-对撞指针)
LeetCode刷题---167. 两数之和 II - 输入有序数组(双指针-对撞指针)
|
3月前
|
存储
LeetCode热题 首题 两数之和
LeetCode热题 首题 两数之和
19 1
|
3月前
|
索引 容器
双指针解决leetcode1两数之和
双指针解决leetcode1两数之和
19 0
|
1月前
|
存储 算法
《LeetCode 热题 HOT 100》——寻找两个正序数组的中位数
《LeetCode 热题 HOT 100》——寻找两个正序数组的中位数
|
1月前
|
网络协议
《 LeetCode 热题 HOT 100》——无重复字符的最长子串
《 LeetCode 热题 HOT 100》——无重复字符的最长子串
|
1月前
《LeetCode 热题 HOT 100》—— 两数相加
《LeetCode 热题 HOT 100》—— 两数相加
|
1月前
leetcode热题100. 字母异位词分组
leetcode热题100. 字母异位词分组
16 0
|
1月前
leetcode热题100.二叉树中的最大路径和
leetcode热题100.二叉树中的最大路径和
18 0
|
1月前
|
算法
leetcode热题100.三数之和
leetcode热题100.三数之和
17 1