Leetcode:1.Two Sum

栏目: Python · 发布时间: 6年前

内容简介:原题连接:内容描述:
这是崔斯特的第八十九篇原创文章

Leetcode:1.Two Sum

1. Two Sum

难度: Easy

刷题内容

原题连接: https://leetcode.com/problems/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].

解题方案

思路 1

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

暴力解法,两轮遍历

beats 12.80%

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]
Runtime: 5248 ms, faster than 12.80% of Python3 online submissions forTwo Sum.
Memory Usage: 13.5 MB, less than 51.76% of Python3 online submissions for Two Sum.

太吓人,遍历太慢了。

思路 2

A + B = target,同样的:A = target - B,我们可以维护一个字典来记录说访问过的值。

这里我犯了个错,我先贴代码

class Solution:
    def twoSum(self, nums: List[int], target: int)-> List[int]:
        lookup = {}
        for i, j in enumerate(nums):
            if target - j not in lookup.values():
                lookup[i] = j
            else:
                return [i, nums.index(target - i)]
Runtime: 568 ms, faster than 34.25% of Python3 online submissions forTwo Sum.
Memory Usage: 14.1 MB, less than 9.73% of Python3 online submissions for Two Sum.

虽然比第一种解法好,但是才超过34.25%,这也太慢了吧。

其实是我写法不够好,字典维序反了,这样查找会慢很多,每次查找都需要查询 lookup.values() ,这其实是一个列表,应该就是这里导致速度变慢。

改良后的代码:

class Solution:
    def twoSum(self, nums: List[int], target: int)-> List[int]:
        lookup = {}
        for i, j in enumerate(nums):
            if target - j in lookup:
                return [i, nums.index(target - j)]
            else:
                lookup[j] = i
Runtime: 40 ms, faster than 73.58% of Python3 online submissions for Two Sum.
Memory Usage: 14.1 MB, less than 10.10% of Python3 online submissions for Two Sum.

比73.58%的要快,果然细节决定成败啊。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Web2.0策略指南

Web2.0策略指南

艾米 / 2009-3 / 39.00元

《Web2.0策略指南》是有关战略的。书中的示例关注的是Web 2.0的效率,而不是聚焦于技术。你将了解到这样一个事实:创建Web 210业务或将Web 2.0战略整合到现在业务中,意味着创建一个吸引人们前来访问的在线站点,让人们愿意到这里来共享他们的思想、见闻和行动。当人们通过Web走到一起时,结果可能远远大于各部分的和。随着传统的“口碑传诵”助推站点高速成长,客户本身就能够帮助建立站点。 ......一起来看看 《Web2.0策略指南》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具