605. Can Place Flowers
605.1 题目描述:
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.
605.2 解题思路:
思路一:两步一处理,开头和结尾分开处理。遍历flowerbed,首先,如果i==0,并且f[i]==0,f[i+1]==0,则n–,标记0个数的flag=0。然后进入循环,如果f[i]==1,则flag=0;否则,flag++。如果flag==2,且f[i+1]==0,则n–,flag=0。最后i++。遍历结束,如果到结尾,flag==1,且f[i]==0,n–。然后返回n<+0。即可。思想就是两个一组同为0来讨论。
思路二:三个一组来讨论。正常思路都应该这样!遍历flowerbed,如果f[i]==0,i==0或者f[i-1]==0,i==f.size-1或者f[i+1]==0,即这三个条件同时满足,说明可以种花,则f[i]==1,为了下一个条件判断准备,然后n–。当遍历结束后,如果n<=0,即花种完了,则返回true,否则false。
605.3 C++代码:
1、思路一代码(25ms):
class Solution120 {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
if (n <= 0)
return false;
if (flowerbed.size() == 1)
{
if (flowerbed[0] == 0 && n == 1)
return true;
else
return false;
}
if (flowerbed.size() == 2)
{
if (flowerbed[0] == 0 && flowerbed[1] == 0 && n == 1)
return true;
else
return false;
}
if (n > (flowerbed.size() / 2 + 1))
return false;
int flag1 = 0;
int i = 0;
if (flowerbed[i] == 0 && flowerbed[i+1] == 0)
{
n--;
flag1 = 0;
i++;
}
while(i < flowerbed.size()-1)
{
if (flowerbed[i]==1)
flag1 = 0;
else
flag1++;
if (flag1 == 2 && flowerbed[i+1] == 0)
{
n--;
flag1 = 0;
}
i++;
}
if (flag1 == 1 && flowerbed[i] == 0)
n--;
return n<=0;
}
};
2、思路二代码(19ms)
class Solution120_1 {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
for (int i = 0; i < flowerbed.size();i++)
{
if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) && (i == flowerbed.size() - 1 || flowerbed[i + 1] == 0))
{
flowerbed[i] = 1;
n--;
}
}
return n <= 0;
}
};
605.4 Python代码:
1、思路二代码(59ms)
class Solution(object):
def canPlaceFlowers(self, flowerbed, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
for i in range(len(flowerbed)):
if flowerbed[i]==0 and (i==0 or flowerbed[i-1]==0) and (i==len(flowerbed)-1 or flowerbed[i+1]==0):
flowerbed[i]=1
n-=1
return n<=0