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;
    }
    
  • 相关阅读:
    支付弹出窗口被拦截解决办法
    实现Bootstrap Carousel Fade Transition 淡入淡出效果
    SVN Global ignore pattern 忽略文件正则后缀
    css 不确定元素宽度的水平居中
    Android Studio运行程序,检测不到(夜神、Genymotion)模拟器
    HttpClient
    Eclipse中复制android项目后要改动的地方
    Eclipse快捷键
    Xml解析之PULL解析 例2
    Xml解析之PULL解析 例1
  • 原文地址:https://www.cnblogs.com/luozhiyun/p/8340765.html
Copyright © 2011-2022 走看看