zoukankan      html  css  js  c++  java
  • 605. Can Place Flowers

    package LeetCode_605
    
    /**
     * 605. Can Place Flowers
     * https://leetcode.com/problems/can-place-flowers/
     * 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.
    Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n,
    return if n new flowers can be planted in the flowerbed 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
    
    Constraints:
    1. 1 <= flowerbed.length <= 2 * 10^4
    2. flowerbed[i] is 0 or 1.
    3. There are no two adjacent flowers in flowerbed.
    4. 0 <= n <= flowerbed.length
     * */
    class Solution {
        /*
        * solution: check current position prev and next if empty or not from left to right,
        * Time:O(n), Space:O(1)
        * */
        fun canPlaceFlowers(flowerbed: IntArray, n: Int): Boolean {
            if (flowerbed == null || flowerbed.isEmpty()) {
                return false
            }
            var count = 0
            var previous = 0
            var next = 0
            var i = 0
            while (i < flowerbed.size && count < n) {
                //if current is empty
                if (flowerbed[i] == 0) {
                    /*
                    * in start and last position, set it's prev and next to 0, for example [0,0,1,0,1],
                    * we can put flower in position 0
                    * */
                    previous = if (i == 0) 0 else flowerbed[i - 1]
                    next = if (i == flowerbed.size - 1) 0 else flowerbed[i + 1]
                    if (previous == 0 && next == 0) {
                        //put flower in
                        flowerbed[i] = 1
                        count++
                    }
                }
                i++
            }
            return count == n
        }
    }
  • 相关阅读:
    Business Objects 基础
    常用的bw基础知识
    SAP BW传输请求操作步骤
    FI/CO 财务基础知识
    SAP财务常用数据源概览
    HANA 和 SAP NetWeaver BW
    Request.QueryString中文乱码
    完全备份类型
    SQL Server备份属于I/O密集型操作
    SQL Server 通过发布订阅 实现数据库同步
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/14235091.html
Copyright © 2011-2022 走看看