【LeetCode】【1.two sum】(python版)

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

思路
方法一:暴力搜索,最简单也是最容易想到的方法,两层嵌套遍历数组,计算和,时间复杂度为 O ( n 2 )
方法二:两次遍历,一次遍历将数组下标和对应值放入hash表中,第二次遍历计算 target - num[i] 的值,在hash表中查找是否存在该结果,时间复杂度 O ( n ) ,空间复杂度 O ( n )
方法三:一次遍历,一边访问数组,计算与target的差值,如果结果不存在hash表中,就把当前数组值和下标加入hash表,如果存在直接返回结果。时间复杂度 O ( n ) ,空间复杂度 O ( n )

后两种方法实现如下:

class Solution(object):
    def twoSum2(self, nums, target):
        value_index = dict()
        for i in range(len(nums)):
            value_index[nums[i]] = i
        for i in range(len(nums)):
            diff = target - nums[i]
            if diff in value_index:
                return [i, value_index.get(diff)]
        return []

    def twoSum3(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        value_index = dict()
        for i in range(len(nums)):
            diff = target - nums[i]
            if diff in value_index:
                return [value_index.get(diff), i]
            value_index[nums[i]] = i
        return []

猜你喜欢

转载自blog.csdn.net/qq_20141867/article/details/80946241