leetcode练习(35,38) python实现

本文解析了两道经典编程题目,一是寻找目标值在有序数组中的插入位置,二是生成count-and-say序列的第n项。通过具体示例和Python代码实现,详细介绍了算法思路。

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

题35

题目要求:给定一个list nums,其中的数按顺序排列,然后再给一个int 数。如果该数在list中,就返回该数在list中的下标,如果不在,就依照大小顺序在合适的位置插入这个数,返回这个下标。
我的思路是:一个for循环,if条件:如果该数等于list就返回该数所在下标,if条件:如果该数小于list中某个数,就返回list那个数的下标。如果循环结束都没有返回,说明该数比list中所有数都大,所以返回len(nums).
代码如下:

class Solution(object):
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        for i in range(len(nums)):
            if target == nums[i]:
                return i
            if target < nums[i]:
                return i
        return len(nums)

nums = [1,2,3,5,6]
s =Solution()
print(s.searchInsert(nums,3))

结果:
这里写图片描述

这里写图片描述

题38

题目要求:实现一个count and say list
The count-and-say sequence is the sequence of integers with the first five terms as following:

  1. 1
  2. 11
  3. 21
  4. 1211
  5. 111221
    1 is read off as “one 1” or 11.
    11 is read off as “two 1s” or 21.
    21 is read off as “one 2, then one 1” or 1211.
    Given an integer n, generate the nth term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:

Input: 1
Output: “1”
Example 2:

Input: 4
Output: “1211”

我的思路是:
找count and say 排列的方法是:
看上一次的count and say排列:
1.若有n个连续一样的数x出现,则本次应输出nx。
2.若当前数x与后一个数不一样,则应输出1x
例如:上一次是1211
对应本次:
1.第一个数1和第二个数2不一样,所以输出11
2.第二个数2和第三个数1不一样,所以输出12
3.第三个数1和第四个数1一样,所以输出21
所以总的输出是111221
再例如下一次:
1.第一个数1和后两个数都一样,所以输出31
2.跳到第四个数,第四个数2和第五个数2一样,所以输出22
3.第六个数只有唯一一个1,所以输出11
所以送的输出是312211
在编程实现时注意:
1.为了判断最后一个数,需要在数的末尾补一个0
2.连续n次出现的数,用count判断重复出现的次数,添加输出后,在循环里要跳过count+1个数,然后count要置0
3.当循环遇到0,就break跳出循环

代码如下:

class Solution(object):
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        strn="1"
        for i in range(n-1):
            strtmp = ""
            strn+="0"
            j=0
            count=0
            while j <= len(strn)-1:
                if strn[j]=="0":
                    break
                if strn[j] == strn[j + 1]:
                    count += 1
                    j+=1
                else:
                    if count>0:
                       strtmp += (str(count+1)+strn[j-1])
                       count=0
                       j+= count+1
                    else:
                        strtmp += "1" + strn[j]
                        j+=1
            strn = strtmp


        return strn

s = Solution()
print(s.countAndSay(6))

结果如下:
这里写图片描述

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值