LeetCode刷题-1

起因

一直以来,我是鄙夷刷题的,总觉得和高中的刷题有些类似,毕竟自己大学了,还要玩这种东西,觉得很没意思。

昨天深夜(3:00)和室友夜谈,聊到了刷题的意义,他是做纯开发,举例说刷过题的人写出 的代码会高效很多,附带了一些例子,听完觉得很有道理,于是立一个刷题的flag。

LeetCode 1

题目 : https://leetcode.com/problems/two-sum/description/

我的解答

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        i = 0
        while(i < len(nums)):
            the_other = target - nums[i]
            j = i + 1
            while(j < len(nums)):
                if(the_other == nums[j]):
                    return i,j
                j = j + 1
            i = i + 1         
        return null

image.png

  • 时间复杂度:O(n^2)
  • 空间复杂度:O(1)

讨论区优秀回答

class Solution:
    def twoSum(self, nums, target):
        nums_hash = {}
        for i in range(len(nums)):
            if target - nums[i] in nums_hash: 
                return [nums_hash[target - nums[i]], i]
            nums_hash[nums[i]] = i

优点在于利用dict的优势,取值为O(1)

  • 时间复杂度:O(n)
  • 空间复杂度:O(n) 由于引入了nums_hash = {},所以空间复杂度上升
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值