leetcode-贪心-605. 种花问题

时间:2021-08-09
本文章向大家介绍leetcode-贪心-605. 种花问题,主要包括leetcode-贪心-605. 种花问题使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
class Solution {
public:
    bool canPlaceFlowers(vector<int>& flowerbed, int n) {
        int count = 0;
        int len = flowerbed.size();

        // 针对长度为0的情况
        if(len==0)
            return false;

        // 针对长度为1的情况
        if(len==1){
            if(flowerbed[0]==0){
                if(n<=1)
                return true;
                else
                return false;
            }
            else{
                if(n==1)
                return false;
                else
                return true;
            }
        }
        for(int i = 0; i < len; i++){
            // i==0 判断起始情况
            if(i==0){
                if(flowerbed[i]==1)
                    continue;
                else if(flowerbed[i+1]==0){
                    count++;
                    flowerbed[i] = 1;
                }
            // i==len-1 判断末尾情况情况   
            }else if(i==len-1){
                if(flowerbed[i] == 1)
                    continue;
                else if(flowerbed[i-1]==0){
                    flowerbed[i] = 1;
                    count++;
                }
            // 中间情况
            }else{
                if(flowerbed[i]==1) // 当前等于1直接跳过
                    continue;
                else if(flowerbed[i-1]==0&&flowerbed[i+1]==0){  // 判断两边是否为0
                    flowerbed[i]=1;
                    count++;
                }
            }
            // if(flowerbed[i]==1)
            //     continue;
            // else if(i==0)
        }
        if(count >= n)  // 题目要求种植的树木之只要小于n都是可以的
            return true;
        else 
            return false;
    }
};

进阶版

class Solution {
public:
    bool canPlaceFlowers(vector<int>& flowerbed, int n) {
        vector<int> res;

        // 就是在上一次的基础上,在首尾添加了一个0,避免了边界判断
        res.push_back(0);
        for(int i = 0; i < flowerbed.size(); i++){
            res.push_back(flowerbed[i]);
        }
        res.push_back(0);

        int len = res.size();
        int count = 0; 

        for(int i = 1; i < len-1; i++){
            if(res[i]==1)  // 提高速度
                continue;
            if(res[i]==0&&res[i-1]==0&&res[i+1]==0){  
                // 判断两边是否为0
                res[i]=1;
                count++;
            }
        }

        if(count >= n)  // 题目要求种植的树木之只要小于n都是可以的
            return true;
        else 
            return false;
    }
};

原文地址:https://www.cnblogs.com/ymec/p/15118651.html