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 if (find(flowerbed.begin(), flowerbed.end(), 1) == flowerbed.end()) 5 {//if there was no flower 6 return (flowerbed.size() + 1) / 2 >= n; 7 } 8 9 int size = flowerbed.size(); 10 int start = 0, end = 0, count = 0; 11 int max = 0; 12 for (int i = 0; i < size; ++i) 13 { 14 if (flowerbed[i] == 0) 15 { 16 ++count; 17 } 18 else 19 { 20 max += count / 2; 21 start = count; 22 count = 0; 23 break; 24 } 25 } 26 27 for (int i = size - 1; i >= 0; --i) 28 { 29 if (flowerbed[i] == 0) 30 { 31 ++count; 32 } 33 else 34 { 35 max += count / 2; 36 end = size - count; 37 count = 0; 38 break; 39 } 40 } 41 42 for (int i = start; i < end; ++i) 43 { 44 if (flowerbed[i] == 0) 45 { 46 ++count; 47 } 48 else 49 { 50 max += (count - 1) / 2; 51 count = 0; 52 } 53 } 54 55 return max >= n ? true : false; 56 } 57 };
贴一个技巧性强一点的discuss的解答,很给力=。=
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 };