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

    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;
    }
    
  • 相关阅读:
    gdb简易教程
    使用WoeUSB在Linux上制作Win10启动盘
    How to fix git: new blank line at EOF
    使用CSS3动画属性实现各种旋转跳跃
    jQuery事件
    挖矿程序minerd入侵分析和解决办法
    css3的伪(伪类和伪元素)大合集
    HTML 5 <blockquote><p>的分工与合作
    HTML<figure> <figcaption> 标签定义图文并茂
    监听 返回按钮事件
  • 原文地址:https://www.cnblogs.com/luozhiyun/p/8340765.html
Copyright © 2011-2022 走看看