用pyhon刷LeetCode(一)

本文分享了作者使用Python解决LeetCode上的编程题目经验,包括两数之和、翻转整数及判断回文数等问题的不同解法,特别是通过字典优化搜索效率的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

感觉自己编程能力亟待提高,今日起用Python刷LeetCode,每天至少两道题,希望能坚持下去!!!立下flag!!

No.1 两数之和:

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

方法一:暴力搜索:

def twoSum(self,nums,target):
    for i in range(len(nums)):
        for j in range(i+1,len(nums)):
            if nums[i]+nums[j]==target:
                return [i,j]

此方法时间复杂度高,复杂用例耗时太久,不能通过。

方法二:用一个字典记录每一个元素的索引和值,只需遍历一次

每遍历一个元素与字典 中已有的元素比较,若相加等于目标值则返回,若不满足便把其放入字典中。

class Solution:
    def twoSum(self, nums, target):
           dic=dict()
           for index,value in enumerate(nums):
               sub=target-value
               if sub in dic:
                  return [dic[sub],index]
               else:
                 dic[value]=index
        

耗时68ms,战胜56.35%的Python3提交记录。

python相关知识:

(1)dict 字典

dict采用键值对(key-value)存储

>>> dic={'one':1,'two':2,'three':3}
>>> dic['one']
1
>>> dic['four']
Traceback (most recent call last):
  File "<input>", line 1, in <module>
KeyError: 'four'
>>> dic['four']=4
>>> dic['four']
4

(2)enumerate()函数,同时获得列表的索引和数值

nums=[1,3,32,2]
>>> for index,value in enumerate(nums):
...     print (index,value)
... 
0 1
1 3
2 32
3 2
No.2  翻转整数

给定一个 32 位有符号整数,将整数中的数字进行反转。

示例 1:

输入: 123
输出: 321

 示例 2:

输入: -123
输出: -321

示例 3:

输入: 120
输出: 21

注意:

假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231,  231 − 1]。根据这个假设,如果反转后的整数溢出,则返回 0。

方法一:每次通过除以10取余得到最后一位,然后进行反转。注意检查是否溢出

import operator
class Solution:
    def reverse(self, x):
        Int_max=2**31-1
        Int_min=-2**31
        ans=0
        while x!=0:
            pop=x-int(x/10)*10
            x=int(x/10)
            if (ans>int(Int_max/10) or (ans==int(Int_max/10) and pop>7))or(ans<int(Int_min/10) or (ans==int(Int_min/10) and pop<-8)):
                return 0
            ans = pop + ans * 10
        return ans

Python知识:

python除法:

>>> 2/3

0.6666666666666666

整除:

>>> 3//2
1
>>> -3//2

-2

Python整数为向下整除

取余:

>>> 3%2
1
>>> -3%2

1

如果要用Python实现向零取整(即正数时向下取整,负数时向上取整,也是本题需要的),可用int(a/b)

>>> int(-3/2)
-1

方法二:转成字符串后用list切片操作

class Solution:
    def reverse(self, x):
       if x<0:
            x=abs(x)
            rev=-int(str(x)[::-1])
       else:
            rev=int(str(x)[::-1])
       if -pow(2,31)<rev<pow(2,31)-1:
            return rev
       else:
            return 0

No.3 回文数

方法一:转字符串再比较

  def isPalindrome(self, x):
        if x<0:
            return False
        return x==int(str(x)[::-1])

方法二:反转一半

    def isPalindrome(self, x):
        if x<0 or (x%10==0 and x!=0):
            return False
        rev=0
        while x>rev:
            rev=rev*10+x%10
            x=x//10
        return (x==rev or x==rev//10)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值