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%的要快,果然细节决定成败啊。


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

查看所有标签

猜你喜欢:

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

Computer Age Statistical Inference

Computer Age Statistical Inference

Bradley Efron、Trevor Hastie / Cambridge University Press / 2016-7-21 / USD 74.99

The twenty-first century has seen a breathtaking expansion of statistical methodology, both in scope and in influence. 'Big data', 'data science', and 'machine learning' have become familiar terms in ......一起来看看 《Computer Age Statistical Inference》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具