605. Can Place Flowers


题目

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.

遍历数组

def canPlaceFlowers(flowerbed, n):
    """
    :type flowerbed: List[int]
    :type n: int
    :rtype: bool
    """
    index = 0
    while n and index < len(flowerbed):
        if flowerbed[index] == 0 and (index == 0 or flowerbed[index - 1] == 0) and (
                index == len(flowerbed) - 1 or flowerbed[index + 1] == 0):
            n -= 1
            index += 2
        else:
            index += 1
    return False if n else True

改进

  • [0, 0, 0, 0]可以种2朵花,而[1, 0, 0, 0, 0, 1]只能种一朵花
  • [0, 0, 1, ... ]和[..., 1, 0, 0]可以种一朵花
def canPlaceFlowers(flowerbed, n):
    """
    :type flowerbed: List[int]
    :type n: int
    :rtype: bool
    """
    count = 1  # [1]
    ret = 0
    for i in flowerbed:
        if not i:
            count += 1
        else:
            if count >= 3:
                ret += (count - 1) // 2  # [2]
            count = 0
    if count >= 2:  # [3]
        ret += count // 2
    return ret >= n
  • [1]处,是针对[0, 0, 1]这种情况
  • [2]处,是针对2边均已种植的方式.3个空位->一朵,4个->一朵,5个->2朵...
  • [3]处,是针对[1, 0, 0]这种情况
优质内容筛选与推荐>>
1、Js事件触发列表与解说(转)
2、Integer VS AtomicInteger VS MutableInteger
3、HTML5+CSS3设计界面
4、《世界是数字的》读后感
5、Java 之 字符输入流[Reader]


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号