LeetCode:Can Place Flowers - 花坛插花

原创
2017/09/25 18:02
阅读数 295

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.

中文:

有一个花坛,用数组表示,0表示当前位置还没有花,1表示当前位置有一朵花,现在你手上有n朵花,要把这n朵花插到花坛中去。但要注意,任意两朵花不能相邻。

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
分享
返回顶部
顶部