https://leetcode.com/problems/can-place-flowers/description/
Solution 1. add 0 to both side for convenience.
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
if(n == 0) return true;
if(flowerbed.size() == 0) return false;
flowerbed.insert(flowerbed.begin(),0);
flowerbed.push_back(0);
for(int i=1; i<flowerbed.size()-1; i++) {
if(flowerbed[i-1] + flowerbed[i] + flowerbed[i+1] == 0) {
i++;
n--;
}
}
return n<=0;
}
Solution 2.
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
if(n == 0) return true;
if(flowerbed.size() == 0) return false;
int z = flowerbed[0] ? 0 : 2, res = 0; // a 0 at beginning counted as 2
for(int i=1; i<flowerbed.size(); i++) {
if(flowerbed[i] == 1 && flowerbed[i-1] == 0) {
res += (z-1)/2;
z = 0;
if(res>=n) return true;
}
else if(flowerbed[i] == 0 && flowerbed[i-1] == 1) {
z = 1;
}
else if(flowerbed[i] == 0) z++;
else continue;
}
res += z/2;
if(res>=n) return true;
return false;
}
No comments:
Post a Comment