题目
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
解题思路
边遍历数组,边将数字及出现的位置存在字典里,当target减去当前的数,出现在字典中,返回结果
代码
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dic = {}
for i, n in enumerate(nums):
if target - n in dic:
return [dic[target - n], i]
dic[n] = i
视频讲解 YouTube<--欢迎点击订阅
视频讲解 bilibili<--欢迎点击订阅
-
Previous
LeetCode 1339 Maximum Product of Splitted Binary Tree (Python) -
Next
LeetCode 36 Valid Sudoku (Python)
Related Issues not found
Please contact @MaxMing0 to initialize the comment