【Leetcode_总结】38. 报数 - python

本文深入解析了报数序列算法,通过实例展示了如何生成报数序列的第n项。介绍了两种实现方法,一种是利用预置列表进行迭代计算,另一种是使用临时变量优化效率。

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

Q:

报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:

1.     1
2.     11
3.     21
4.     1211
5.     111221

1 被读作  "one 1"  ("一个一") , 即 11
11 被读作 "two 1s" ("两个一"), 即 21
21 被读作 "one 2",  "one 1" ("一个二" ,  "一个一") , 即 1211

给定一个正整数 n(1 ≤ n ≤ 30),输出报数序列的第 n 项。

注意:整数顺序将表示为一个字符串。

示例 1:

输入: 1
输出: "1"

示例 2:

输入: 4
输出: "1211"

思路:这个题目看了好久才明白,(⊙_⊙)?。。思路就是先把题目中算好的几个数放到一个list里面,如果目标值在这个范围内,直接返回结果,如果不在,就算算吧,计算就是使用一个双指针,统计一下数量,然后加上对应的几个几就好了,效率有些低,代码如下:

class Solution:
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        res = ['1','11','21','1211','111221']
        if n <=5:
            return res[n-1]
        for i in range(4,31):
            slow = 0
            fast = 1
            nums = ''
            count = 1
            print(res[i])
            while fast < len(res[i]):
                if res[i][slow] == res[i][fast]:
                    count+=1
                    fast+=1
                else:
                    nums+=str(count)+str(res[i][slow])
                    slow = fast
                    fast+=1
                    count = 1
            nums+=str(count)+str(res[i][slow])
            res.append(nums)
            print(res)
            if i== n-2 :
                return res[i+1]

放一个效率比较高的代码作为范本吧,其实思路是一样的,为啥差了这么多毫秒-_-|| 可能是往list里面存储消耗时间了

class Solution:
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        res = '1'
        for _ in range(n - 1):
            cur = res[0]
            count = 0
            temp = ''
            for i in res:
                if i == cur:
                    count += 1
                else:
                    temp += str(count) + cur
                    cur = i
                    count = 1
            temp += str(count) + cur
            res = temp
        return res

 将原先的res删除,换成一个temp = ''作为中间变量,代码如下:

class Solution:
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        res = ['1','11','21','1211','111221']
        if n <= 5:
            return res[n-1]
        nums = '111221'
        for i in range(4, n):
            temp = ""
            slow = 0
            fast = 1
            count = 1
            while fast < len(nums):
                if nums[slow] == nums[fast]:
                    count+=1
                    fast+=1
                else:
                    temp+=str(count)+str(nums[slow])
                    slow = fast
                    fast+=1
                    count = 1
            temp+=str(count)+str(nums[slow])
            nums = temp
        return nums

 效率稍有提升:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值