The Solution to Leetcode 605 Can Place Flowers

解决一个经典的编程问题,即在遵循特定规则的情况下确定是否可以在给定的花坛中种植指定数量的新鲜花。此问题需要考虑边界条件并进行逻辑判断。

Question:

Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, flowers cannot be planted in adjacent plots - they would compete for water and both would die.

Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a number n, return if nnew flowers can be planted in it without violating the no-adjacent-flowers rule.

假设你有一个长的花坛,其中一些地块种植,有些不是。 然而,花朵不能种植在相邻的地块上 - 他们会争取水,两者都会死亡。
给定一个花坛(表示为包含0和1的数组,其中0表示空,1表示不为空),数字n,如果可以种植n个新鲜花,则不返回无相邻花规则。

Example 1:

Input: flowerbed = [1,0,0,0,1], n = 1
Output: True

Example 2:

Input: flowerbed = [1,0,0,0,1], n = 2
Output: False

Note:

  1. The input array won't violate no-adjacent-flowers rule.
  2. The input array size is in the range of [1, 20000].
  3. n is a non-negative integer which won't exceed the input array size.

注意:输入数组不会违反无相邻花规则。
           输入数组大小在[1,20000]的范围内。
           n是不会超过输入数组大小的非负整数。

思路:首先判断对于给定的数组,能够放多少数字1进去。有两个相邻的数字1就返回false.对于是数字0的元素,要检查左右两边的数字是不是0,如果是0,就可以放1,对于第一个数字,只用判断右边的数字是不是0,对于最后一个数字,只用判断左边的数字是不是0.最后求得一共能放进去1的数字的个数q与输入的n对比,如果q大于等于n,那么就返回true,否则false。

Answer:

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

Run code result:

Your input
[1,0,0,0,1]
2
Your answer
false
Expected answer
false

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值