leetcode 605. 种花问题

it2025-03-29  13

我的想法是,如果第i个花坛的左右都是空的话,在这个花坛就种下花,即,flowerbed[i]=1并且n--,表示种下了一朵。然后遍历完整个数组后,判断n朵花是不是都种完了。在这里要注意边界,边界只需要判断它的一侧是不是可以种花。然后还有特殊情况是只有一个花坛时,所以我又把它单独拎出来判断。

 

这道题我的代码用时48ms,而且也写的真的很丑 - -

class Solution { public: bool canPlaceFlowers(vector<int>& flowerbed, int n) { int length = flowerbed.size(); if(n>((length+1)/2)) return false; if(length == 1) { if(flowerbed[0] == 1) { if(n>0) return false; }else if(n<=1) return true; } for(int i = 0;i<length;++i) { if(flowerbed[i] == 0) { if(i>=1 && i<length-1) { if( (flowerbed[i-1] == 0) && (flowerbed[i+1] == 0)) { flowerbed[i] = 1; n--; } }else if(i == 0){ if(flowerbed[i+1] == 0) { flowerbed[i] = 1; n--; } }else if(i == length-1){ if(flowerbed[i-1] == 0) { flowerbed[i] = 1; n--; } } } } if(n <= 0) return true; return false; } };

 

最新回复(0)