Can Place Flowers(C++种花问题)

解题思路:

依次判断每个数和它前后是否均为0,可以栽花的话,就将此位置赋值1

class Solution {
public:
    bool canPlaceFlowers(vector<int>& flowerbed, int n) {
    	int length = flowerbed.size();
        if (length == 1) {
        	if (flowerbed[0]+n<2) return true;
        	else return false;
		}
        int count = 0;
        if (flowerbed[0]==flowerbed[1] && flowerbed[0]==0) {
        	flowerbed[0]=1;
			count++;
		} 
        if (count>=n) return true;
        for (int i=1;i<length-1;i++) {
        	if (flowerbed[i-1]==0 && flowerbed[i]==0 && flowerbed[i+1]==0) {
        		count++;
        		if (count>=n) return true;
        		flowerbed[i]=1;
                i++;
			}
		}
        if (flowerbed[length-1]==flowerbed[length-2] && flowerbed[length-1]==0) count++;
        return count>=n;
    }
};
发布了264 篇原创文章 · 获赞 272 · 访问量 42万+

猜你喜欢

转载自blog.csdn.net/coolsunxu/article/details/105482529