• 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;
    }
    
  • 相关阅读:
    python读取excel保存到mysql
    python读取mysql返回json
    在C#后台使用MD5值对文件进行加
    使用文件流的形式上传大文件
    IE8兼容性问题
    解决 CentOS 下找不到库文件的问题
    openssl/ossl_typ.h:没有那个文件或目录
    解决 VSCode 进行 C/C++ 开发时 gcc 依赖缺失问题
    VSCode 中进行 C/C++ 开发需要的配置文件
    记一下使用 WeBASE 搭建自己的联盟链过程
  • 原文地址:https://www.cnblogs.com/luozhiyun/p/8340765.html
Copyright © 2020-2023  润新知