605. 种花问题

一、题目描述

假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去。
给定一个花坛(表示为一个数组包含0和1,其中0表示没种植花,1表示种植了花),和一个数 n 。能否在不打破种植规则的情况下种入 n 朵花?能则返回True,不能则返回False。
示例 1:
输入: flowerbed = [1,0,0,0,1], n = 1
输出: True
示例 2:
输入: flowerbed = [1,0,0,0,1], n = 2
输出: False
注意:
数组内已种好的花不会违反种植规则。
输入的数组长度范围为 [1, 20000]。
n 是非负整数,且不会超过输入数组的大小。

二、题解
方法一:
计算两个1中间有几个0,如果有n个,则可以种(n-1)/2朵花

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

方法二:连跳两格
如果遇到1,那么下一个一定是0,所以连跳两格如果是0,判断其下一位是否是0,如果是,说明当前位置可以种花。

class Solution {
public:
    bool canPlaceFlowers(vector<int>& flowerbed, int n) {
        int size = flowerbed.size();
        for(int i=0;i<size;i+=2){
            if(flowerbed[i]==0){
                if(i==size - 1 || flowerbed[i+1]==0)
                    n--;
                else
                    i++;
            }
        }
        
        return n<=0;
    }
};
上一篇:Codeforces Round #605 (Div. 3) F. Two Bracket Sequences


下一篇:646