当前位置:   article > 正文

Leetcode第一题 两数之和 Python解法_leetcode第一题用python

leetcode第一题用python

Leetcode第一题《两数之和》( Python解法)

博主本科统计,虽然硕士是计算机专业,现在研二了,这代码水平甚是尴尬,只要能实现功能就ok,性能什么的真的太差了,所以决定从今天起开始刷Leetcode,2天一道,希望可以坚持。

一、题目描述

该题目很简单,题目描述如下图,在此不赘述。
在这里插入图片描述

二、多种解法

2.1 简单粗暴2层循环

class Solution:
    # 最简单粗暴的2层循环遍历,结果就是超时了,想哭
    # 时间复杂度:O(n^2),空间复杂度O(1) 
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in range(len(nums)-1):
            for j in range(i+1, len(nums)):
                if nums[i] + nums[j] == target:
                    m = [i,j]
                    break
        return m
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

2.2 改进为1层循环
相对于第一种方法,主要提升在于:将2层for循环替换为1层。没有超时了,但时间复杂度和空间复杂度无本质变化。

class Solution:
    # 只用一遍循环遍历
    # 查找target-nums[left_index]是否在剩余数组里出现
    # 如果找得到,则返回其下标值;反之则说明没有该答案
    # 时间复杂度:O(n^2),空间复杂度O(1) 
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        answer = []
        for left_index in range(len(nums)):
            right = target - nums[left_index]
            if right in nums[left_index+1:]:
                nums_right = nums[left_index+1:]
                right_index = nums_right.index(right) + left_index + 1
                answer.extend([left_index,right_index])
                break
        return answer
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

提交后的结果,这个用时还是太多。
在这里插入图片描述
2.3 使用dict模拟hash结构
代码如下,空间换时间。

class Solution:
    # 使用dict字典
    # 时间复杂度:O(n),空间复杂度O(n) 
    def twoSum(self, nums:List[int], target:int) -> List[int]:
        re_nums_dict = {}
        for nums_key, nums_value in enumerate(nums):
            re_nums_dict[nums_value] = nums_key
            
        for left_index, left in enumerate(nums):
            right_index = re_nums_dict.get(target-left)
            if right_index != left_index and right_index is not None:
                break
        return [left_index, right_index]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

提交答案,时间性能得到飞跃,空间始终没变。。。
在这里插入图片描述

三、反思

从最终的时间和空间复杂度排名可以看到,这个进步空间还是很大的。
等刷到后边题目有了新的想法再回过头来做改进。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/457005
推荐阅读
相关标签
  

闽ICP备14008679号