leetcode 记录

38 count-and-say

用到递归,在比较最后一个字符的时候有点麻烦

class Solution(object):
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        if n <=0:
            return False
        if n == 1:
            return '1'
        if n == 2:
            return '11'
        if n >= 3:
            finalAnswr = ''
            lastAnswr = self.countAndSay(self, n-1) # 这里括号中的这个self有异议,在我自己电脑上IDE需要加,提交的时候就不需要
            base_str = lastAnswr[0]
            base_count = 1


            for i in range(len(lastAnswr)-1):
                cmp_str = lastAnswr[i+1]
                if cmp_str == base_str:
                    base_count += 1
                    if i == len(lastAnswr)-2:
                        finalAnswr = finalAnswr + str(base_count) + base_str

                else:
                    finalAnswr = finalAnswr + str(base_count) + base_str
                    base_str = cmp_str
                    base_count = 1
                    if i == len(lastAnswr)-2:
                        finalAnswr = finalAnswr + cmp_str + '1'

            return finalAnswr


26 remove-duplicates-from-sorted-array

关键是不能占用更多内存。

判断和前面最开始的是不是一样,如果不一样就在base_compare的下一个位置写这个新数据

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) <= 1:
            return len(nums)
        slow = 0
        for i in range(1, len(nums)):
            if nums[i] != nums[slow]:
                slow += 1
                nums[slow] = nums[i]
        return nums

11 盛最多水的容器

正常写循环很简单,但是超时间了。

设置左右挡板,谁小谁往前走。用while

    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        leftp = 0
        rightp = len(height)-1
        max_area = 0

        while leftp < rightp:

            area = (rightp - leftp) * min(height[rightp], height[leftp])
            if area > max_area:
                max_area = area

            if height[leftp] < height[rightp]:
                leftp += 1
            else:
                rightp -= 1
        return max_area

 

阅读更多
个人分类: LeetCode积累
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭