leetcode练习(35,38) python实现

题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))

结果:
leetcode练习(35,38) python实现_第1张图片

这里写图片描述

题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))

结果如下:
leetcode练习(35,38) python实现_第2张图片

leetcode练习(35,38) python实现_第3张图片

你可能感兴趣的:(leetcode练习,python,leetcode)