605. Can Place Flowers
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
含义:这道题给了我们一个01数组,其中1表示已经放了花,0表示可以放花的位置,但是有个限制条件是不能有相邻的花。为给定的n朵花能否放置完毕
解法1
1 public boolean canPlaceFlowers(int[] flowerbed, int n) { 2 int count = 0; 3 for(int i = 0; i < flowerbed.length && count < n; i++) { 4 if(flowerbed[i] == 0) { 5 //get next and prev flower bed slot values. If i lies at the ends the next and prev are considered as 0. 6 int next = (i == flowerbed.length - 1) ? 0 : flowerbed[i + 1]; 7 int prev = (i == 0) ? 0 : flowerbed[i - 1]; 8 if(next == 0 && prev == 0) { 9 flowerbed[i] = 1; 10 count++; 11 } 12 } 13 } 14 15 return count == n; 16 }
解法2
1 if (n == 0) return true; 2 if (flowerbed.length == 0) return false; 3 if (flowerbed.length == 1) { 4 if (flowerbed[0] == 1) { 5 return false; 6 } 7 return n > 1 ? false : true; 8 } 9 if (flowerbed.length == 2) { 10 if (n == 1) { 11 if (flowerbed[0] + flowerbed[1] == 0) return true; 12 return false; 13 } 14 return false; 15 } 16 if (flowerbed[0] + flowerbed[1] == 0) { 17 flowerbed[0] = 1; 18 n--; 19 } 20 for (int i = 1; i <= flowerbed.length - 2; i++) { 21 if (flowerbed[i - 1] + flowerbed[i] + flowerbed[i + 1] == 0) { 22 flowerbed[i] = 1; 23 n--; 24 } 25 } 26 27 if (n > 0) { 28 if (flowerbed[flowerbed.length - 2] + flowerbed[flowerbed.length - 1] == 0) { 29 flowerbed[flowerbed.length - 1] = 1; 30 n--; 31 } 32 } 33 34 return n > 0 ? false : true;