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;
    }
    
  • 相关阅读:
    【SQL】CASE与DECODE
    【SQL】通过rowid查找及删除重复记录
    【SQL】联合语句
    【PLSQL】游标
    【SQL】IN、EXISTS和表连接三者的效率比较
    【SQL】CONNECT BY 层次化查询
    【SQL】MERGE
    【SQL】多表查询
    【Python算法】遍历(Traversal)、深度优先(DFS)、广度优先(BFS)
    【Python算法】归纳、递归、归简
  • 原文地址:https://www.cnblogs.com/luozhiyun/p/8340765.html
Copyright © 2011-2022 走看看