https://leetcode.com/problems/can-place-flowers/description/
First version:
class Solution { public: bool canPlaceFlowers(vector<int>& flowerbed, int n) { int m = flowerbed.size(); if (n > (m+1) / 2) return false; for (int i = 0; i < m && n > 0; i++) { if (flowerbed[i] == 1) i++; else { if ((i == 0 || flowerbed[i-1] == 0) && (i == m-1 || flowerbed[i+1] == 0)) { flowerbed[i] = 1; i++; n--; } } } return n == 0; } };
V2:
class Solution { public: bool canPlaceFlowers(vector<int>& flowerbed, int n) { int m = flowerbed.size(); if (n > (m+1) / 2) return false; for (int i = 0; i < m && n > 0; i++) { if (flowerbed[i] == 1 || i > 0 && flowerbed[i-1] == 1) continue; if (i == m - 1 || flowerbed[i+1] == 0) n--; i++; } return n == 0; } };