Golang Leetcode 605. Can Place Flowers.go

本文解析了一道关于在花坛中种植花卉的算法题目,重点在于如何在已有的花坛布局中找到合适的空位种植花卉,同时遵循每朵花之间至少需要一个空位的规则。文章详细介绍了算法思路及其实现代码,通过计数器记录可以种植的花卉数量,最终判断是否能够满足种植目标。

思路

注意处理位置在首尾的情况

code

func canPlaceFlowers(flowerbed []int, n int) bool {
	cnt := 0
	for i := 0; cnt < n && i < len(flowerbed); i++ {
		if i > 0 && flowerbed[i-1] == 1 {
			continue
		}
		if i < len(flowerbed)-1 && flowerbed[i+1] == 1 {
			continue
		}
		if flowerbed[i] != 0 {
			continue
		}
		flowerbed[i] = 1
		cnt++
		if i < len(flowerbed)-1 {
			flowerbed[i+1] = -1
		}
	}
	return cnt >= n
}

更多内容请移步我的repo:https://github.com/anakin/golang-leetcode

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值