LC1. Two Sum

Description

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

Solution

  • Brute Force:

    遍历nums,对每个元素遍历它之后的所有元素,时间复杂度, 空间复杂度

  • Hash:

    因为每个元素都是要找its complement, 所以complement可以作为一个index,对应的位置存储这个元素的位置。使用hash达到的时间复杂度,的空间复杂度。

    class Solution:
        def twoSum(self, nums: List[int], target: int) -> List[int]:
            value = {}
            for i in range(len(nums)):
                if nums[i] in value.keys():
                    return [value[nums[i]], i]
                else:
                    value[target-nums[i]] = i
    

Tips

  • 实测发现使用for i in range(len(nums)) 比for i, x in enumerate(nums) 更快诶

你可能感兴趣的:(LC1. Two Sum)