apachecn / apachecn-algo-zh

ApacheCN 数据结构与算法译文集
https://algo.apachecn.org/
11k stars 2.19k forks source link

第7题和第14题 #238

Closed xshahq closed 5 years ago

xshahq commented 5 years ago

1. Two Sum

难度: Easy

刷题内容

原题连接

内容描述

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

解题方案

思路 1 **- 时间复杂度: O(N^2)**- 空间复杂度: O(1)**

暴力解法,两轮遍历

beats 27.6%

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)):
            for j in range(i+1, len(nums)):
                if nums[i] + nums[j] == target:
                    return [i, j]
        return []

思路 2 **- 时间复杂度: O(N)**- 空间复杂度: O(N)**

上面的思路1太慢了,我们可以牺牲空间换取时间

          2        7        11    15
         不存在   存在之中
lookup   {2:0}    [0,1]
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        look_up = {}
        for i, num in enumerate(nums):
            if target-num in look_up:
                return [look_up[target-num], i]
            look_up[num] = i
        return []