【二次过】Lintcode 1138: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.

 Notice

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.

Example
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

解题思路:

    满足放置花的条件是当前位置以及它前一个与后一个位置的数均为0,才能放置一个花,所以这里使用指针遍历一遍若满足上述条件就把当前位置置1,且将记录的数量nums加1,继续考察下一个元素直到尾部。这个时候就统计出了这个花圃能放下最多花的数量nums,将其与n进行比较即可知道能否满足。

    需要注意的是首尾元素的特殊性,可以将头部元素的左边与尾部元素的右边插入0保持其性质。

class Solution {
public:
    /**
     * @param flowerbed: an array
     * @param n: an Integer
     * @return: if n new flowers can be planted in it without violating the no-adjacent-flowers rule
     */
    bool canPlaceFlowers(vector<int> &flowerbed, int n) 
    {
        // Write your code here
        if(n == 0)
            return true;
            
        flowerbed.insert(flowerbed.begin(),0);
        flowerbed.push_back(0);
        
        int nums = 0;
        for(auto pt = flowerbed.begin()+1;pt != flowerbed.end()-1;pt++)
        {
            if(*(pt-1)==0 && *(pt+1)==0 && *pt == 0)
            {
                *pt = 1;
               nums++;
            }
        }
        
        if(nums >= n)
            return true;
        else
            return false;
        
    }
};


猜你喜欢

转载自blog.csdn.net/majichen95/article/details/80385188
今日推荐