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
    }
}
复制代码

 

posted @   johnny_zhao  阅读(100)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2020-01-05 543. Diameter of Binary Tree
点击右上角即可分享
微信分享提示