1. 程式人生 > >Leetcode: Two Sum — python

Leetcode: Two Sum — python

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

  1. enumerate() gets the index and the values of a list
  2. charge whether a value is in a list or not:num in list, return true or false