【LeetCode605】-种花问题

方法一

实现思路

就是尽量靠最左边或靠最优边种花,如果不可行尽量在前面只隔一个种花

实现代码

class Solution {
    
    
public:
    bool canPlaceFlowers(vector<int>& flowerbed, int n) {
    
    
        if(flowerbed.size()==1&&!flowerbed[0]&&n<=1) return true;
        for(int i=1;i<flowerbed.size();i++){
    
    
            if(n==0) break;
            if(!flowerbed[i-1]&&!flowerbed[i]){
    
    
                if(i==flowerbed.size()-1||i==1)
                {
    
    
                    int index=i;
                    if(i==1) index=index-1;
                    flowerbed[index]=1;
                    n--;
                }
                else if(!flowerbed[i+1]){
    
    
                    flowerbed[i]=1;
                    n--;
                }
                
            }
            
        }
        return !n;
    }
};

提交结果及分析

在这里插入图片描述
时间复杂度O(n)

方法二

实现思路

为了方便统一化处理,可以在头添加一个0,尾添加一个0,那样就可以实现判断一个元素左右两边及自己都为0,就可以在自己的位置种花
从左到右遍历,能种就种

猜你喜欢

转载自blog.csdn.net/weixin_44944046/article/details/113801671