美文网首页
LC1. Two Sum

LC1. Two Sum

作者: M_cory | 来源:发表于2019-04-12 12:21 被阅读0次

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,对每个元素遍历它之后的所有元素,时间复杂度O(n^2)=(n-1)+(n-2)+\cdots+1, 空间复杂度O(1)

  • Hash:

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

    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

      本文链接:https://www.haomeiwen.com/subject/ehxcwqtx.html