难度简单8803收藏分享切换为英文关注反馈
给定一个整数数组 nums
和一个目标值 target
,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
自己的做法:
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 target == nums[i] + nums[j]:
return [i,j]
执行结果:
通过
显示详情
执行用时:6364 ms, 在所有 Python3 提交中击败了7.19%的用户
内存消耗:14.7 MB, 在所有 Python3 提交中击败了65.17%的用户
大神解法:链接:https://leetcode-cn.com/problems/two-sum/solution/xiao-bai-pythonji-chong-jie-fa-by-lao-la-rou-yue-j/
def two_sum(nums, target):
"""这样写更直观,遍历列表同时查字典"""
dct = {}
for i, n in enumerate(nums):
if target - n in dct:
return [dct[target - n], i]
dct[n] = i
for循环对list nums遍历,enumerate(nums),字典dct中是是将列表的 值 存储为 键,巧妙,键 存储为 值,如果字典中存在这个键,则说明找到,直接返回该键的值即为列表的键。dct[n] = i是将列表所有元素添加到字典中。