|
| 1 | +假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去。 |
| 2 | +给定一个花坛(表示为一个数组包含0和1,其中0表示没种植花,1表示种植了花),和一个数 n 。能否在不打破种植规则的情况下种入 n 朵花?能则返回True,不能则返回False。 |
| 3 | +示例: |
| 4 | +```python |
| 5 | +输入: flowerbed = [1,0,0,0,1], n = 1 |
| 6 | +输出: True |
| 7 | +输入: flowerbed = [1,0,0,0,1], n = 2 |
| 8 | +输出: False |
| 9 | +``` |
| 10 | +#### 方法一: |
| 11 | +遍历数组,如果一个元素是0,并且它的左右两个元素都是0,那就可以种花,并把该位置改为1,特殊情况,数组第一个元素,与数组最后一个元素,特殊处理。 |
| 12 | +```python |
| 13 | +def canPlaceFlowers(flowerbed, n): |
| 14 | + length = len(flowerbed) |
| 15 | + count = 0 |
| 16 | + if length == 1 and flowerbed[0] == 0: |
| 17 | + count += 1 |
| 18 | + else: |
| 19 | + for i in range(0, length): |
| 20 | + if i == 0: |
| 21 | + # 最左边 |
| 22 | + if flowerbed[i] == 0 and flowerbed[i+1] == 0: |
| 23 | + count += 1 |
| 24 | + flowerbed[i] = 1 |
| 25 | + elif i == len(flowerbed)-1: |
| 26 | + # 最右边 |
| 27 | + if flowerbed[i] == 0 and flowerbed[i-1] == 0: |
| 28 | + count += 1 |
| 29 | + flowerbed[i] = 1 |
| 30 | + else: |
| 31 | + # 中间 |
| 32 | + if flowerbed[i] == 0 and flowerbed[i-1] == 0 and flowerbed[i+1] == 0: |
| 33 | + count += 1 |
| 34 | + flowerbed[i] = 1 |
| 35 | + if count >= n: |
| 36 | + return True |
| 37 | + return False |
| 38 | +``` |
| 39 | +#### 优化:执行过程中,如果count已经大于n了,直接返回结果 |
| 40 | +```python |
| 41 | +def canPlaceFlowers(flowerbed, n): |
| 42 | + length = len(flowerbed) |
| 43 | + count = 0 |
| 44 | + if length == 1 and flowerbed[0] == 0: |
| 45 | + count += 1 |
| 46 | + if count >= n: |
| 47 | + return True |
| 48 | + else: |
| 49 | + for i in range(0, length): |
| 50 | + if i == 0: |
| 51 | + # 最左边 |
| 52 | + if flowerbed[i] == 0 and flowerbed[i+1] == 0: |
| 53 | + count += 1 |
| 54 | + flowerbed[i] = 1 |
| 55 | + elif i == len(flowerbed)-1: |
| 56 | + # 最右边 |
| 57 | + if flowerbed[i] == 0 and flowerbed[i-1] == 0: |
| 58 | + count += 1 |
| 59 | + flowerbed[i] = 1 |
| 60 | + else: |
| 61 | + # 中间 |
| 62 | + if flowerbed[i] == 0 and flowerbed[i-1] == 0 and flowerbed[i+1] == 0: |
| 63 | + count += 1 |
| 64 | + flowerbed[i] = 1 |
| 65 | + if count >= n: |
| 66 | + return True |
| 67 | + return False |
| 68 | +``` |
0 commit comments