、
最直接的想法就是直接二分去找答案,枚举天数,当天数不是最小值时,条件总能满足,当天数不能在小时,条件不能满足。
难点是,对于给定天数limit,如何确定是否满足答案,由于必须用相邻的花制作,所以这样枚举即可。
bool check(vector<int>& bloomDay, int m, int k, int limit){
int cnt= 0, flower = 0;
for(int i = 0; i < bloomDay.size(); i++){
if(bloomDay[i] <= limit){
flower++;
if(flower >= k){
cnt++;
flower = 0;
}
}else{
flower = 0;
}
}
return cnt >= m;
}
完整代码
class Solution {
public:
int minDays(vector<int>& bloomDay, int m, int k) {
// 二分,枚举最小的天数,看是否符合要求
if(bloomDay.size() < m * k){
return -1;
}
int left = 1, right = 0;
for(auto day : bloomDay){
right = max(right, day);
}
while(left <= right){
int mid = (left + right) / 2;
if(check(bloomDay, m, k, mid)){
right = mid - 1;
}else{
left = mid + 1;
}
}
return left;
}
bool check(vector<int>& bloomDay, int m, int k, int limit){
int cnt= 0, flower = 0;
for(int i = 0; i < bloomDay.size(); i++){
if(bloomDay[i] <= limit){
flower++;
if(flower >= k){
cnt++;
flower = 0;
}
}else{
flower = 0;
}
}
return cnt >= m;
}
};