[leetcode] 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

Note:

  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.

分析:题目意思还是很清晰的,给定数组a,由0、1组成,规则是:1不能连续出现。要求在a中查找满足条件可以将多少个0变成1。

这里就需要考虑三种情况:开头、末尾和中间。

代码如下:

 1 class Solution {
 2     public boolean canPlaceFlowers(int[] flowerbed, int n) {
 3         int count = 0;
 4         int i = 0;
 5         if ( flowerbed.length == 1){
 6             if ( flowerbed[0] == 1 ) {
 7                 if ( n == 0 ) return true;
 8                 else return false;
 9             }
10             else 
11                 return n<=1;
12         }
13         while ( i < flowerbed.length ){
14             if ( flowerbed[i] == 0 && (i==0||flowerbed[i-1]==0) && (i==flowerbed.length-1||flowerbed[i+1]==0) ){
15                 flowerbed[i]=1;
16                 count ++;
17                 i+=2;
18                 if ( i >= flowerbed.length ) break;
19             }
20             else{
21                 i ++;
22             }
23         }
24         return count >= n;
25         
26     }
27 }

    运行时间6ms。

 

 

这个题目没什么太需要总结的,就是考虑好特殊情况,整理好思路就好了。

posted @ 2018-09-27 17:48  Lin.B  阅读(172)  评论(0编辑  收藏  举报