layout:     posttitle:      PHP 计算种花问题
subtitle:   PHP 计算种花问题
date:       2020-05-28
author:     he xiaodong
header-img: img/default-post-bg.jpg
catalog: true
tags:
- Go
- PHP
- LeetCode
- 计算种花问题
计算种花问题
假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去。
给定一个花坛(表示为一个数组包含 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 是非负整数,且不会超过输入数组的大小。
 
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/can-place-flowers
解题思路
假设 num = [0,0,1,0],num[-1] != 1 得 True, num[4] !=1 得 True,那就不用做什么边界识别。指针从下标 0 开始,该下标对应的值不为 1,左边不为 1,右边不为 1,种花,顺便 count++。指针移到最后 count>=n 就是可以了。
PHP 实现
class Solution {/*** @param Integer[] $flowerbed* @param Integer $n* @return Boolean*/function canPlaceFlowers($flowerbed, $n) {$length = count($flowerbed);$count = 0;for ($i = 0; $i < $length; $i++) {if ($flowerbed[$i-1] !== 1 && $flowerbed[$i] !== 1 && $flowerbed[$i+1] !== 1) {$flowerbed[$i] = 1;++$count;}}return $count >= $n;}}
© 原创文章
