【leetcode】605. Can Place Flowers(Python & C++)
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