|
| 1 | +# 605.种花问题 |
| 2 | + |
| 3 | + |
| 4 | +[url](https://leetcode-cn.com/problems/longest-harmonious-subsequence/) |
| 5 | + |
| 6 | + |
| 7 | +## 题目 |
| 8 | +假设有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花不能种植在相邻的地块上,它们会争夺水源,两者都会死去。 |
| 9 | + |
| 10 | +给你一个整数数组 flowerbed 表示花坛,由若干 0 和 1 组成,其中 0 表示没种植花,1 表示种植了花。另有一个数 n ,能否在不打破种植规则的情况下种入 n 朵花?能则返回 true ,不能则返回 false。 |
| 11 | + |
| 12 | + |
| 13 | + |
| 14 | +``` |
| 15 | +输入:flowerbed = [1,0,0,0,1], n = 1 |
| 16 | +输出:true |
| 17 | +输入:flowerbed = [1,0,0,0,1], n = 2 |
| 18 | +输出:false |
| 19 | +``` |
| 20 | + |
| 21 | + |
| 22 | +## 方法 |
| 23 | + |
| 24 | + |
| 25 | +## code |
| 26 | + |
| 27 | +### js |
| 28 | + |
| 29 | +```js |
| 30 | +let canPlaceFlowers = (flowerbed, n) => { |
| 31 | + if (n < 0) |
| 32 | + return false; |
| 33 | + let cnt = 0; |
| 34 | + let len = flowerbed.length; |
| 35 | + for (let i = 0; i < len; i++) { |
| 36 | + if (flowerbed[i] === 1) |
| 37 | + continue; |
| 38 | + let pre = i === 0 ? 0 : flowerbed[i - 1]; |
| 39 | + let next = i === len - 1 ? 0 : flowerbed[i + 1]; |
| 40 | + if (pre === 0 && next === 0) { |
| 41 | + cnt++; |
| 42 | + flowerbed[i] = 1; |
| 43 | + } |
| 44 | + } |
| 45 | + return cnt >= n; |
| 46 | +}; |
| 47 | +console.log(canPlaceFlowers([1,0,0,0,1], 1)); |
| 48 | +console.log(canPlaceFlowers([1,0,0,0,1], 2)); |
| 49 | +``` |
| 50 | + |
| 51 | +### go |
| 52 | + |
| 53 | +```go |
| 54 | +func canPlaceFlower(flowerbed []int, n int) bool { |
| 55 | + if n < 0 { |
| 56 | + return false |
| 57 | + } |
| 58 | + cnt := 0 |
| 59 | + l := len(flowerbed) |
| 60 | + for i := 0; i < l; i++ { |
| 61 | + if flowerbed[i] == 1{ |
| 62 | + continue |
| 63 | + } |
| 64 | + pre, next := 0, 0 |
| 65 | + if i == 0 { |
| 66 | + pre = 0 |
| 67 | + } else { |
| 68 | + pre = flowerbed[i - 1] |
| 69 | + } |
| 70 | + if i == l - 1 { |
| 71 | + next = 0 |
| 72 | + } else { |
| 73 | + next = flowerbed[i + 1] |
| 74 | + } |
| 75 | + if pre == 0 && next == 0 { |
| 76 | + cnt++ |
| 77 | + flowerbed[i] = 1 |
| 78 | + } |
| 79 | + } |
| 80 | + return cnt >= n |
| 81 | +} |
| 82 | +``` |
| 83 | + |
| 84 | +### java |
| 85 | + |
| 86 | +```java |
| 87 | +class Solution { |
| 88 | + public boolean canPlaceFlowers(int[] flowerbed, int n) { |
| 89 | + // 边界? |
| 90 | + if (n < 0) return false; |
| 91 | + int cnt = 0; |
| 92 | + int len = flowerbed.length; |
| 93 | + for (int i = 0; i < len; i++) { |
| 94 | + // 判断是1的 |
| 95 | + if (flowerbed[i] == 1) continue; |
| 96 | + int pre = i == 0 ? 0 : flowerbed[i - 1]; |
| 97 | + int next = i == len - 1 ? 0 : flowerbed[i + 1]; |
| 98 | + if (pre == 0 && next == 0) { |
| 99 | + cnt++; |
| 100 | + flowerbed[i] = 1; |
| 101 | + } |
| 102 | + } |
| 103 | + return cnt >= n; |
| 104 | + } |
| 105 | +} |
| 106 | +``` |
| 107 | + |
0 commit comments