本文主要是介绍605. Can Place Flowers(Leetcode每日一题-2021.01.01)--抄答案,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Problem
You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.
Given an integer array flowerbed containing 0’s and 1’s, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule.
Constraints:
- 1 <= flowerbed.length <= 2 * 104
- flowerbed[i] is 0 or 1.
- There are no two adjacent flowers in flowerbed.
- 0 <= n <= flowerbed.length
Example1
Input: flowerbed = [1,0,0,0,1], n = 1
Output: true
Example2
Input: flowerbed = [1,0,0,0,1], n = 2
Output: false
Solution
class Solution {
public:bool canPlaceFlowers(vector<int>& flowerbed, int n) {if (!n) return true;int res = 0;for (int i = 0; i < flowerbed.size(); i ++ ) {if (flowerbed[i]) continue;//统计连续0的个数int j = i;while (j < flowerbed.size() && !flowerbed[j]) j ++ ;int k = j - i - 1;if (!i) k ++ ;//左边是边界if (j == flowerbed.size()) k ++ ;//右边是边界res += k / 2;if (res >= n) return true;i = j;}return false;}
};
这篇关于605. Can Place Flowers(Leetcode每日一题-2021.01.01)--抄答案的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!