- Can Place Flowers
Suppose you have a long flowerbed in which some of the pots are planted and some are not. However, flowers cannot be planted in adjacent plots - they would compete for water and both would die.
Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a number n, return if n new flowers can be planted in it without violating the no-adjacent-flowers rule.
Example
Example 1:
Input: flowerbed = [1,0,0,0,1], n = 1
Output: True
Example 2:
Input: flowerbed = [1,0,0,0,1], n = 2
Output: False
Notice
1.The input array won’t violate no-adjacent-flowers rule.
2.The input array size is in the range of [1, 20000].
3.n is a non-negative integer which won’t exceed the input array size.
解法:
我的解法是分析1和0的规律。
101 gap = 1 -> 0 tree
1001 gap = 2 -> 0 tree
10001 gap = 3 -> 1 tree
100001 gap = 4 -> 1 tree
1000001 gap = 5 -> 2 trees
10000001 gap = 6 -> 2 trees
100000001 gap = 7 -> 3 trees
1000000001 gap = 8 - 3 trees
可知两个1中间可种的树数目为 (gap + 1) / 2 - 1。
而gap = p2 - p1 -1。
用双指针p1, p2遍历vector。p2和p1分别记录下新旧1的位置(p2前,p1后)。p2初始化为0,p1初始化为-1。
class Solution {
public:
/**
* @param flowerbed: an array
* @param n: an Integer
* @return: if n new flowers can be planted in it without violating the no-adjacent-flowers rule
*/
bool canPlaceFlowers(vector<int> &flowerbed, int n) {
int len = flowerbed.size();
if ((len == 0) || (len < n)) return false;
int p1 = -1, p2 = 0; //p2 is ahead of p1
while (p2 < len) {
while(flowerbed[p2] == 0) p2++;
if (p2 > 0) {
int gap = p2 - p1 - 1; //gap is the available slots between 1s, such as 1---1
n -= (gap + 1) / 2 - 1;
p1 = p2;
}
p2++;
}
if (n == 0) return true;
else return false;
}
};
解法2:九章的解法,不用双指针,直接遍历,但逻辑较复杂。
public class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
int count = 0;
for (int i = 0; i < flowerbed.length; i++) {
if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0)
&& (i == flowerbed.length - 1 || flowerbed[i + 1] == 0)) {
flowerbed[i] = 1;
count++;
}
if (count >= n) {
return true;
}
}
return false;
}
}
解法2:
在原vector的前后各加一个0,就可以利用公式flowerCount += (zeroCount - 1) >> 1;
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
flowerbed.insert(flowerbed.begin(), 0);
flowerbed.push_back(0);
int bedSize = flowerbed.size();
int zeroCount = 0, flowerCount = 0;
for (int i = 0; i < bedSize; i++) {
if (flowerbed[i] == 1) {
flowerCount += (zeroCount - 1) >> 1;
zeroCount = 0;
} else {
zeroCount++;
}
}
flowerCount += (zeroCount - 1) >> 1;
return flowerCount >= n;
}
};