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]这种情况
posted @ 2018-02-09 15:15  Yuanoung  阅读(87)  评论(0)    收藏  举报