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:

  1. 输入: flowerbed = [1,0,0,0,1], n = 1
  2. 输出: True

示例 2:

  1. 输入: flowerbed = [1,0,0,0,1], n = 2
  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 实现

  1. class Solution {
  2. /**
  3. * @param Integer[] $flowerbed
  4. * @param Integer $n
  5. * @return Boolean
  6. */
  7. function canPlaceFlowers($flowerbed, $n) {
  8. $length = count($flowerbed);
  9. $count = 0;
  10. for ($i = 0; $i < $length; $i++) {
  11. if ($flowerbed[$i-1] !== 1 && $flowerbed[$i] !== 1 && $flowerbed[$i+1] !== 1) {
  12. $flowerbed[$i] = 1;
  13. ++$count;
  14. }
  15. }
  16. return $count >= $n;
  17. }
  18. }

© 原创文章

最后恰饭 阿里云全系列产品/短信包特惠购买 中小企业上云最佳选择 阿里云内部优惠券