当前位置:网站首页>Leetcode (605) -- flower planting
Leetcode (605) -- flower planting
2022-06-25 23:30:00 【SmileGuy17】
Leetcode(605)—— The problem of planting flowers
subject
Suppose there's a very long flower bed , Part of the plot is planted with flowers , The other part didn't . But , Flowers cannot be planted on adjacent plots , They compete for water , Both will die .
Give you an array of integers flowerbed Indicates a flower bed , By a number of 0 and 1 form , among 0 No flowers ,1 It means flowers are planted . There's another number n , Can it be planted without breaking the planting rules n A flower ? Energy returns true , If not, return false.
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
Tips :
1 <= flowerbed.length <= 2 * 104
flowerbed[i] by 0 or 1
flowerbed There are no two adjacent flowers
0 <= n <= flowerbed.length
source : Power button (LeetCode)
link :https://leetcode.cn/problems/can-place-flowers
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .
Answer key
Method 1 : Greedy Algorithm
Ideas
Judge whether you can plant in the flower bed without breaking the planting rules n n n A flower , From the perspective of greed , You should plant as many flowers as possible without breaking the planting rules , Then judge whether the maximum number of flowers that can be planted is greater than or equal to n n n.
Suppose the subscript of the flower bed i i i And subscripts j j j Flowers are planted everywhere , among j − i ≥ 2 j-i \ge 2 j−i≥2, And subscript [ i + 1 , j − 1 ] [i+1,j-1] [i+1,j−1] No flowers are planted in the range , Only when the j − i ≥ 4 j-i \ge 4 j−i≥4 Can only be subscript i i i And subscripts j j j Plant more flowers between , And the subscript range of flowers that can be planted is [ i + 2 , j − 2 ] [i+2,j-2] [i+2,j−2]. The number of places where flowers can be planted is p = j − i − 3 p=j-i-3 p=j−i−3, When p p p If it is an odd number, it can be planted in this range at most ( p + 1 ) / 2 (p+1)/2 (p+1)/2 A flower , When p p p If the number is even, it can be planted in this range at most p / 2 p/2 p/2 A flower . Because when p p p When it's even , Under the rule of integer division p / 2 p/2 p/2 and ( p + 1 ) / 2 (p+1)/2 (p+1)/2 equal , So no matter p p p Is it odd or even , Can be planted within this range at most ( p + 1 ) / 2 (p+1)/2 (p+1)/2 A flower , That is, it can be planted within this range at most ( j − i − 2 ) / 2 (j-i-2)/2 (j−i−2)/2 A flower .
The above is the case of planting flowers between two existing flowers ( There is no other flower between the two flowers ). Suppose the subscript of the flower bed l l l At the left is the flower that has been planted , Subscript r r r On the far right is the flower that has been planted ( That is, for any k < l k<l k<l or k > r k>r k>r There are flowerbed [ k ] = 0 \textit{flowerbed}[k]=0 flowerbed[k]=0), How to calculate the subscript l l l The maximum number of flowers that can be planted on the left and the subscript r r r How many flowers can you plant on the right ?
Subscript l l l On the left l l l A place , When l < 2 l<2 l<2 Cannot subscript l l l Plant flowers on the left , When l ≥ 2 l \ge 2 l≥2 Can be in the subscript range [ 0 , l − 2 ] [0,l-2] [0,l−2] Plant flowers within the range , The number of places where flowers can be planted is l − 1 l-1 l−1, It can be planted at most l / 2 l/2 l/2 A flower .
Make m m m Is an array flowerbed \textit{flowerbed} flowerbed The length of , Subscript r r r On the right m − r − 1 m-r-1 m−r−1 A place , The number of places where flowers can be planted is m − r − 2 m-r-2 m−r−2, It can be planted at most ( m − r − 1 ) / 2 (m-r-1)/2 (m−r−1)/2 A flower .
If there are no flowers on the flower bed , Then there are m m m There are four places to plant flowers , It can be planted at most ( m + 1 ) / 2 (m+1)/2 (m+1)/2 A flower .
According to the above calculation method , Calculate the maximum number of flowers that can be planted in the flower bed , Judge whether it is greater than or equal to n n n that will do . The specific methods are as follows .
- maintain prev \textit{prev} prev Indicates the subscript position of the last planted flower , At the beginning prev = − 1 \textit{prev}=-1 prev=−1, Indicates that you have not encountered any flowers that have been planted .
- Traverse the array from left to right flowerbed \textit{flowerbed} flowerbed, When you meet flowerbed [ i ] = 1 \textit{flowerbed}[i]=1 flowerbed[i]=1 According to the prev \textit{prev} prev and i i i Calculate the maximum number of flowers that can be planted in the previous interval , Then make prev = i \textit{prev}=i prev=i, Continue traversing the array flowerbed \textit{flowerbed} flowerbed The remaining elements .
- Traversal array flowerbed \textit{flowerbed} flowerbed After the end , According to the array prev \textit{prev} prev And length m m m Calculate the maximum number of flowers that can be planted in the last interval .
- Judge whether the maximum number of flowers that can be planted in the whole flower bed is greater than or equal to n n n.
Because we only need to judge whether we can plant in the flower bed without breaking the planting rules n n n A flower , There is no need to know exactly how many flowers can be planted in the flower bed , So it can be optimized in the loop , When the number of flowers that can be planted has reached n n n, You can go back to true \text{true} true, There is no need to continue calculating the rest of the array .
Code implementation
my :
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
if(n == 0) return true;
int size = flowerbed.size();
int m = 0;
int lastflower = -2; // In order to deal with [0] 1 In special circumstances
for(int i = 0 ; i < size; i++){
if(flowerbed[i] == 1){
if(lastflower == -1) m += i/2; // (i-0)/2
else m += (i-lastflower-2) > 0? (i-lastflower-2)/2: 0;
if(m >= n) return true;
lastflower = i;
i++; // Skip the next 0
}else if(i == size-1){
// Special circumstances, i.e [0,1,0,0,0]
// In order to deal with [0] 1 In special circumstances , Make lastflower = -2
m += (i-lastflower)/2;
if(m >= n) return true;
}
}
return false;
}
};
Netizens have a very clever idea :
It's enough to judge whether there are flowers in the back . This use 1 The two adjacent sides must be followed by 0, And features at the end .
Because if flowerbed[i]==1 When , it i++ 了 , After one cycle, it will also i++, amount to i Two steps , So there is no need to judge the front .
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
int size = flowerbed.size();
for(int i = 0; i < size; ++i){
if(flowerbed[i] == 0 && (i+1 == size || flowerbed[i+1] == 0)){
n--;
i++;
}else if(flowerbed[i] == 1) i++;
if(n <= 0) return true; // Less than 0 To avoid n For the initial 0 The situation of
}
return false;
}
};
// I wrote the following
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
int size = flowerbed.size();
// Suppose its left adjacency is 0, Then you only need to check whether it and the right are 0 that will do
// Then take care of the special circumstances at the end
for(int i = 0; i < size; i++){
if(flowerbed[i] == 1) i++; // Jump to adjacent 0 Next to , You can ensure that the left side of the next inspection position is 0
else if(((i == size-1 && flowerbed[i] == 0)) || (flowerbed[i] == flowerbed[i+1])){
i++;
n--;
}
if(n <= 0) return true;
}
return false;
}
};
Complexity analysis
Time complexity : O ( m ) O(m) O(m), among m m m It's an array flowerbed \textit{flowerbed} flowerbed The length of . You need to traverse the array once .
Spatial complexity : O ( 1 ) O(1) O(1). The extra space used is constant .
边栏推荐
猜你喜欢

Ue4 Ue5 combine le plug - in de reconnaissance vocale de bureau pour la reconnaissance vocale

Circuit module analysis exercise 5 (power supply)

Ble Low Power Bluetooth networking process and Bluetooth role introduction

多台云服务器的 Kubernetes 集群搭建

How to use drawing comparison function in CAD

软件测试面试一直挂,面试官总是说逻辑思维混乱,怎么办?

经典图像分割网络:Unet 支持libtorch部署推理【附代码】

hiberate核心API/配置文件/一级缓存详解

UE4_UE5结合offline voice recognition插件做语音识别功能
![[opencv450 samples] inpaint restores the selected region in the image using the region neighborhood](/img/36/8ad6034473382f66f315eb70440711.png)
[opencv450 samples] inpaint restores the selected region in the image using the region neighborhood
随机推荐
Implementation of sequence table: static and dynamic
电路模块分析练习5(电源)
Applets - view and logic
UE4 学习记录二 给角色添加骨架,皮肤,及运动动画
23class introduction
【ModuleBuilder】GP服务实现SDE中两个图层相交选取
Leetcode(605)——种花问题
How to add cartoon characters to the blog park?
STM32 development board + smart cloud aiot+ home monitoring and control system
CDN加速是什么
经典图像分割网络:Unet 支持libtorch部署推理【附代码】
多台云服务器的 Kubernetes 集群搭建
C2. k-LCM (hard version)-Codeforces Round #708 (Div. 2)
What aspects should we start with in the feasibility analysis of dry goods?
Multithreaded learning 1
My C language learning process
RK3568+鸿蒙工控板工业网关视频网关解决方案
Idea common plug-ins
Recently prepared to translate foreign high-quality articles
百度:2022年十大热度攀升专业出炉,第一名无悬念!