leetcode刷题(Python)

博主分享了在LeetCode上用Python解题的经验,包括两数之和、整数反转、回文数、罗马数字转整数等题目,分析了自己的解法和效率问题,对比了其他解法,并探讨了动态规划、递归等算法思想在解题中的应用。
摘要由CSDN通过智能技术生成

num1.两数之和

本题难度不大,但是O( n 2 n^2 n2)的复杂度算超时…
我的解法:

class Solution:
    def twoSum(self, nums, target): 
        length = len(nums)
        for i in range(length):
            for j in range(i+1,length):
                if nums[i] + nums[j] == target:
                    result = []
                    result.append(i)
                    result.append(j)
                    return(result)

正确解法:

一开始用首尾递进查找做的,需要一次排序,时间复杂度是 O(nlogn),下面是 Python3 代码:

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        sorted_id = sorted(range(len(nums)), key=lambda k: nums[k]) #key代表排序依据,意为按下标对应的元素大小对元素进行排序,选择使用下标排序的原因是最后输出的是下标而不是数组元素,索引没有直接对元素进行排序
        head = 0
        tail = len(nums) - 1
        sum_result = nums[sorted_id[head]] + nums[sorted_id[tail]]
        while sum_result != target:
            if sum_result > target: #排好序后当首位之和大于目标,则尾减1缩小范围,同理
                tail -= 1
            elif sum_result < target:
                head += 1
            sum_result = nums[sorted_id[head]] + nums[sorted_id[tail]]
        return [sorted_id[head], sorted_id[tail]] #最后收尾缩小到了相加等于目标的元素位置
后来看解答发现可以用字典做,时间复杂度是 O(n),还是太年轻:

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        hashmap = {
   }
        for index, num in enumerate(nums):
            another_num = target - num
            if another_num in hashmap:
                return [hashmap[another_num], index]
            hashmap[num] = index
        return None

num7.整数反转

这道题主要运用的是字符串、列表、数字之间的转换,体现了python3的方便之处

class Solution:
    def reverse(self, x: int) -> int:
        if x >= 0:
            y = list(map(int, str(x))) # 将整数先转换为字符串,map(function, iterable, ...)结果一般使用list进行接收,最后转换为列表

            length = len(y)

            result = []

            for i in range(length):
                result.append(y[length-i-1]) # 这里始终要注意range左闭右开的性质
            a = [str(j) for j in result] # 对列表中的元素进行遍历并转换为字符串,用列表存放
            b = int("".join(a)) #将这些列表中的无缝连接,再转换成整形

            if -2**31 <= b <= 2**31-1:
                return b
            else:
                return 0
    
            return b
        else:
            x = -x
            y = list(map(int, str(x)))

            length = len(y)

            result = []

            for i in range(length):
                result.append(y[length-i-1])
            a = [str(j) for j in result]
            b = int("".join(a))

    
            if -2**31 <= b <= 2**31-1:
                return -b
            else:
                return 0

其他人的答案

class Solution:
    def reverse(self, x: int) -> int:
        s = str(x)[::-1].rstrip('-') #去除掉符号之后直接反转,::对字符串也可以使用
        if int(s) < 2**31:
            if x >=0:
                return int(s)
            else:
                return 0-int(s)
        return  0

num9.回文数

我的,貌似时间还是很长

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x >= 0:    
            y = list(map(int,str(x)))
            count = 0
            for i in range(int(len(y)/2)):   
                if y[i] != y[len(y)-i-1]:
                    count +=1
            if count > 0:
                return False
            else:
                return True
        else:
            return False

其他人的

class Solution:
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x < 0:
            return False
        else:
            y = str(x)[::-1]
            if y == str(x):
                return True
            else: 
                return False

num13.罗马数字转整数

用了比较复杂的算法,调试了很久

class Solution:
    def romanToInt(self, s: str) -> int:
        dict1 = {
   'I' : 1,'V' : 2, 'X' : 3, 'L' : 4, 'C' : 5, 'D' :
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值