leetcode python3 简单难度(答案持续更新)

leetcode中国官方网站-题库

https://leetcode-cn.com/problemset/all/

 

leetcode官网-题库

https://leetcode.com/problemset/all/

 

参考资料

https://blog.csdn.net/minione_2016/article/details/78855124

 

0001.Two_Sum

答案

class Solution(object):
    def twoSum(self,nums,target):
        dic = {}
        for i, num in enumerate(nums):
            if target - num in dic:
                return [dic[target - num],i]
            else:
                dic[num] = i

 

0007.Reverse_Integer

答案1

class Solution(object):
    def reverseInteger(self,n):
        
        rev=0
        n1 = n if n > 0 else -n

        
        #除数余数结合
        while n1:
            rev = rev*10 + n1%10
            n1 = n1//10

            
        if rev > 2**31-1 or rev < -2**31:
            return 0

        return rev if n >0 else -rev

 

答案2

class Solution(object):
    def reverseInteger(self,n):
        n1 = n if n > 0 else -n
        
        #思路:(1)int转为str;(2)str转为list;(3)翻转list;(4)list转str;(5)str转int
        str1 = str(n1)
        list1 = list(str1)
        list2 = list1[::-1]
        str2 = ''.join(list2)
        n2 = int(str2)
        
        if n2 > 2**31-1 or n2 < -2**31:
            return 0

        return n2 if n > 0 else -n2

 

 

0009.Palindrome_Number

答案1

class Solution(object):
    def reverseInteger(self,n):
        
        #思路:(1)int转为str;(2)str转为list;(3)翻转list;(4)判断翻转前后的list是否相同
        str1 = str(n)
        list1 = list(str1)
        list2 = list1[::-1]

        return True if list2 == list1 else False

答案2(进阶)

class Solution(object):
    def reverseInteger(self,n):
        
        #负数一定不是回文数
        if n < 0:
            return False
        
        #思路:除数余数结合,根据翻转后的值与原值是否相等判断该值是否为回文数
        rev = 0
        n1 = n
        while n1 > 0:
            rev = rev*10 + n1%10
            n1 = n1//10
        return rev == n

 

357.

思路:位数累加;最高位数分2种:不含0 和含0

def func(n):
	res = 1
	for i in range(n):
		res *= 9-i
	return res


def main(n):
	num = 1
	if n==0:
		return num
	else:
		for i in range(1,n+1):
			num+=func(i)+func(i-1)*(i-1)
		return num

思路2:遍历,利用set内元素唯一性作为判断依据。缺点:n较大时,耗时极长,因此不考虑此种方法。

def func1(n):
	num = 0
	for i in range(10**n):
		if len(set(str(i)))==len(str(i)):
			num+=1
	return num

耗时对比:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值