前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >605. Can Place Flowers

605. Can Place Flowers

作者头像
luozhiyun
发布2019-09-10 18:45:53
2780
发布2019-09-10 18:45:53
举报

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.

我的答案:

class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < flowerbed.length; i++) {
            if(flowerbed[i] == 1){
                list.add(i);
            }
        }
        if(list.size()==0 ){
            n = n-(flowerbed.length+1)/2;
            return n<=0;
        }
        //head
        Integer head = list.get(0);
        if(head>1){
            n = n-head/2;
        }
        //tail
        Integer tail = list.get(list.size()-1);
        if(flowerbed.length-tail-1>1){
            n = n-(flowerbed.length-tail-1)/2;
        }
        
        for(int i = 0;i<list.size()-1;i++){
            int begin = list.get(i);
            int end = list.get(i+1);
            if(end-begin>2){
                n = n-(end-begin-2)/2;
            }
        }
        
        return n <= 0;
    }
}

大牛的答案:

public boolean canPlaceFlowers(int[] flowerbed, int n) {
    int count = 1;
    int result = 0;
    for(int i=0; i<flowerbed.length; i++) {
        if(flowerbed[i] == 0) {
            count++;
        }else {
            result += (count-1)/2;
            count = 0;
        }
    }
    if(count != 0) result += count/2;
    return result>=n;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-01-24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档