【LeetCode】1. Two Sum(Hash Table)
程序员文章站
2022-03-08 16:45:10
...
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
【题目大意】
在一个整数组成的字符串中找到两个数,使得两个数的和为目标参数。
使用Hash表,在表中nums[i]存储i下标,每次检测target-nums[i] 有没有在表中。
【Code】
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
temp = {}
for i in range(len(nums)):
if nums[i] not in temp:
temp[nums[i]] = i
if target-nums[i] in temp.keys() and temp[target-nums[i]]!=i:
# 防止再一次检测到自身
return [temp[target-nums[i]], i]
人生苦短,我用python。
推荐阅读
-
【LeetCode】Two Sum & Two Sum II - Input array is sorted & Two Sum IV - Input is a BST
-
LeetCode - 1. Two Sum(8ms)
-
LeetCode_#1_两数之和 Two Sum_C++题解
-
LeetCode(62)-Two Sum
-
LeetCode:Two Sum浅析
-
[LeetCode] 1. Two Sum 两数之和
-
leetcode哈希表hash table集合
-
【leetcode】#1 Two Sum【Hash】【Easy】
-
LeetCode 454. 4Sum II (Hash Table)
-
LeetCode 1 Two Sum (hash)