LeetCode-605:Can Place Flowers (可放置花的数量)

Question

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:

  • The input array won’t violate no-adjacent-flowers rule.
  • The input array size is in the range of [1, 20000].
  • n is a non-negative integer which won’t exceed the input array size.

问题解析:

给定0、1数组,0表示空,1表示非空,给定整数n,判断是否可以插入n个1,1不能相邻。

Answer

Solution 1:

简单分情况考虑。

  • 题目看似情况不多,在实际编写过程中还是发现容易忽略很多情况。
  • 首先考虑插入的规则:num个连0,则表示可以插入(num-1)/2个1;
  • 再考虑首尾元素是零的情况,当首位是0或者末位是0,那么只要有两个0则便可以插入1个1,也就是说,首位和末位的一个0可以当做两个0来使用;
  • 最后考虑还有一种情况是,数组为一个0的情况,这个时候可以插入1个1
  • 连续0结束则计算一次剩余需要插入的1的个数。
  • 解法直观,但是没有新意,也容易考虑不周出错。
class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        int count = 0;
        if (flowerbed == null || flowerbed.length == 0) return false;
        if (flowerbed.length == 1 && flowerbed[0] == 0) return true;

        for (int i = 0; i < flowerbed.length && n > 0; i++){
            if (flowerbed[i] == 0){
                if (i == 0 || i == flowerbed.length-1) count++;
                count++;
            }else{
                n -= (count-1)/2;
                count = 0;
            }
        }

        n -= (count-1)/2;
        return n < 1;
    }
}
  • 时间复杂度:O(n),空间复杂度:O(1)
Solution 2:

使用贪心算法。

  • 使用贪心的思想去解决,即只要位置满足条件就立即插入1,直到n == 0或者数组遍历完毕。
  • 同时需要考虑首位和末位是零的情况。
  • 判断条件即判断左右两边分别均是0,只要插入了位置该位置则置1.
class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        for (int idx = 0; idx < flowerbed.length && n > 0; idx ++)
            if (flowerbed[idx]==0 && (idx==0 || flowerbed[idx-1]==0) && 
            (idx==flowerbed.length-1 || flowerbed[idx+1]==0)){
                n--;
                flowerbed [idx] = 1;
            }
        return n == 0;
    }
}
  • 时间复杂度:O(n),空间复杂度:O(1)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值