• leetcode——605.种花问题


    class Solution:
        def canPlaceFlowers(self, flowerbed, n: int) -> bool:
            if 1 not in flowerbed:
                return 2*n-1<=len(flowerbed)
            res=[]
            q=0
            i=0
            j=i+1
            c=flowerbed.index(1)
            if c>1 :
                q+=c//2
            d=flowerbed[::-1].index(1)
            if d>1 :
                q+=d//2
            flowerbed=flowerbed[c:len(flowerbed)-d]
            while j<len(flowerbed):
                if flowerbed[i]==1:
                    i+=1
                else:
                    k=i
                    if flowerbed[k]==0 and flowerbed[k]==flowerbed[j]:
                        k,j=j,j+1
                    else:
                        a=flowerbed[i:j]
                        res.append(a)
                        i=j
                        j+=1
            for i in range(len(res)):
                if len(res[i])>2 and len(res[i])%2==1:
                    q+=len(res[i])//2
                elif len(res[i])>2 and len(res[i])%2==0:
                    q+=len(res[i])//2-1
            return q>=n
    执行用时 :256 ms, 在所有 Python3 提交中击败了43.40%的用户
    内存消耗 :14.4 MB, 在所有 Python3 提交中击败了5.13%的用户
     
    两头和中间分别进行计算。
    执行用时为 56 ms 的范例
    class Solution:
        def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
            if flowerbed.count(1) + n > len(flowerbed)/2 + 1:
                return False
            #前后补零法 将两边同样看做中间对待 减少分类情况
            nums = [0] + flowerbed + [0]
            i = 1
            count = 0
            while i < len(flowerbed)+1:
                if nums[i-1] == 0 and nums[i] == 0 and nums[i+1] == 0:
                    count += 1
                    i += 2
                else:
                    i += 1
            return count >= n

                                                                                                            ——2019.10.9

     
     
     
     
     
    我的前方是万里征途,星辰大海!!
  • 相关阅读:
    Java 密钥库 证书 公钥 私钥
    Theos小例子
    armbian禁用zram
    常见JS混淆器和特征
    命令行工具收藏
    python中生成器的两段代码
    把mysql数据库从windows迁移到linux系统上的方法
    【转载】使用Flink低级处理函数ProcessFunction
    spark读取压缩文件
    SpringBoot系列——validation参数校验
  • 原文地址:https://www.cnblogs.com/taoyuxin/p/11644353.html
Copyright © 2020-2023  润新知