1. Two Sum

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].

解法

使用散列表,把每一个遍历过的数字存储到散列表中。

  • python

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hash_table = {}

        for i, num in enumerate(nums):
            # find one!
            if target - num in hash_table:
                return [hash_table[target - num], i]
            # record current number and its index
            hash_table[num] = i

        # empty list
        return []

只遍历一次,时间复杂度 O(n)O(n);使用散列表,需要额外空间 O(n)O(n)

Last updated

Was this helpful?