zoukankan      html  css  js  c++  java
  • [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。

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

  • 相关阅读:
    html5--html实现乘法口诀表
    html5--switch选择结构的优化
    CSS盒子模型
    html5--项目实战-仿天猫(移动端页面)
    关于运动
    自然拼读法长元音
    揭开自然拼读法(Phonics)的神秘面纱
    ExtJs自学教程(1):一切从API開始
    四个好看的CSS样式表格
    【Linux】linux经常使用基本命令
  • 原文地址:https://www.cnblogs.com/boris1221/p/9714584.html
Copyright © 2011-2022 走看看