605. Can Place Flowers【easy】
Suppose 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 - 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 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
Note:
- The input array won‘t violate no-adjacent-flowers rule.
- The input array size is in the range of [1, 20000].
- n is a non-negative integer which won‘t exceed the input array size.
错误解法:
1 class Solution { 2 public: 3 bool canPlaceFlowers(vector<int>& flowerbed, int n) { 4 int max = 0; 5 int temp = 0; 6 7 for (int i = 0; i < flowerbed.size(); ++i) 8 { 9 if (flowerbed[i] == 0) 10 { 11 temp++; 12 max = temp > max ? temp : max; 13 } 14 else 15 { 16 temp = 0; 17 } 18 } 19 20 21 if ((max - 2) % 2) 22 { 23 return ((max - 2) / 2 + 1 >= n); 24 } 25 else 26 { 27 return ((max - 2) / 2 >= n); 28 } 29 } 30 };
想要用最长连续的0去求,调试了很久,但还是条件判断有问题,这种方法不妥!
参考大神们的解法,如下:
解法一:
1 public class Solution { 2 public boolean canPlaceFlowers(int[] flowerbed, int n) { 3 int count = 0; 4 for(int i = 0; i < flowerbed.length && count < n; i++) { 5 if(flowerbed[i] == 0) { 6 //get next and prev flower bed slot values. If i lies at the ends the next and prev are considered as 0. 7 int next = (i == flowerbed.length - 1) ? 0 : flowerbed[i + 1]; 8 int prev = (i == 0) ? 0 : flowerbed[i - 1]; 9 if(next == 0 && prev == 0) { 10 flowerbed[i] = 1; 11 count++; 12 } 13 } 14 } 15 16 return count == n; 17 } 18 }
解法二:
1 public boolean canPlaceFlowers(int[] flowerbed, int n) { 2 for (int idx = 0; idx < flowerbed.length && n > 0; idx ++) 3 if (flowerbed [idx] == 0 && (idx == 0 || flowerbed [idx - 1] == 0) && (idx == flowerbed.length - 1 || flowerbed [idx + 1] == 0)) { 4 n--; 5 flowerbed [idx] = 1; 6 } 7 return n == 0; 8 }
解法一和解法二都需要随时更新原来数组的状态
解法三:
1 class Solution { 2 public: 3 bool canPlaceFlowers(vector<int>& flowerbed, int n) { 4 flowerbed.insert(flowerbed.begin(),0); 5 flowerbed.push_back(0); 6 for(int i = 1; i < flowerbed.size()-1; ++i) 7 { 8 if(flowerbed[i-1] + flowerbed[i] + flowerbed[i+1] == 0) 9 { 10 --n; 11 ++i; 12 } 13 14 } 15 return n <=0; 16 } 17 };
不更新原来数组的值,通过多移下标来实现
时间: 2024-12-09 15:56:32