# LeetCode：Can Place Flowers - 花坛插花

2017/09/25 18:02

1、题目名称

Can Place Flowers（花坛插花）

2、题目地址

https://leetcode.com/problems/can-place-flowers/description/

3、题目内容

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 n new flowers can be planted in it without violating the no-adjacent-flowers rule.

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.

4、解题方法

/**
* LeetCode 605 - Can Place Flowers
* @文件名称 Solution.java
* @文件作者 Tsybius2014
* @创建时间 2017年9月25日17:15:39
*/
class Solution {

/**
* 花坛插花 - 检测花坛内是否还能种植n朵花
* @param flowerbed
* @param n
* @return
*/
public boolean canPlaceFlowers(int[] flowerbed, int n) {

//没有多余的花要插，一定是满足条件的
if (n <= 0) {
return true;
}

//只有一个空位的情况，直接判断
if (flowerbed.length == 1) {
if (flowerbed[0] == 0) {
if (n <= 1) {
return true;
} else {
return false;
}
} else {
if (n <= 0) {
return true;
} else {
return false;
}
}
}

//先顾首尾
if (flowerbed.length >= 2) {
if (flowerbed[0] == 0 && flowerbed[1] == 0) {
flowerbed[0] = 1;
n--;
if (n == 0) {
return true;
}
}
if (flowerbed[flowerbed.length - 1] == 0 &&
flowerbed[flowerbed.length - 2] == 0) {
flowerbed[flowerbed.length - 1] = 1;
n--;
if (n == 0) {
return true;
}
}
}

//只有左右都无花的情况才能插入一朵花
for (int i = 1; i < flowerbed.length - 1; i++) {
if (flowerbed[i - 1] == 0 && flowerbed[i] == 0 && flowerbed[i + 1] == 0) {
flowerbed[i] = 1;
n--;
if (n == 0) {
return true;
}
}
}

return false;
}
}


END

0
0 收藏

0 评论
0 收藏
0