Leetcode:1.Two Sum

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

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

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


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

查看所有标签

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

ACM国际大学生程序设计竞赛亚洲区预选赛真题题解

ACM国际大学生程序设计竞赛亚洲区预选赛真题题解

郭炜 / 电子工业 / 2011-7 / 49.00元

ACM国际大学生程序设计竞赛(ACM International Collegiate Programming Contest,简称ACM/ICPC)是世界上历史最悠久,规模最大、最具声望的程序设计竞赛,一直受到众多国际知名大学的重视,全球著名IT公司更是争相招募竞赛的优胜者。 该项赛事分为各大洲预选赛和全球总决赛两个阶段。北京大学多次在亚洲区预选赛中负责命题工作,是中国在ACM/ICPC命......一起来看看 《ACM国际大学生程序设计竞赛亚洲区预选赛真题题解》 这本书的介绍吧!

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

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

HEX CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具