Leetcode: Two Sum — python
阿新 • • 發佈:2019-01-03
Leetcode: Two Sum — python
Question
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.
Answer
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
num_set = {}
for num_index, num in enumerate(nums):
if (target-num) in num_set:
return [num_set[target-num], num_index]
num_set[num] = num_index
notes
- enumerate() gets the index and the values of a list
- charge whether a value is in a list or not:num in list, return true or false