Skip to content

Latest commit

 

History

History
107 lines (88 loc) · 2.24 KB

605.种花问题.md

File metadata and controls

107 lines (88 loc) · 2.24 KB

605.种花问题

url

题目

假设有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花不能种植在相邻的地块上,它们会争夺水源,两者都会死去。

给你一个整数数组  flowerbed 表示花坛,由若干 0 和 1 组成,其中 0 表示没种植花,1 表示种植了花。另有一个数 n ,能否在不打破种植规则的情况下种入 n 朵花?能则返回 true ,不能则返回 false。

输入:flowerbed = [1,0,0,0,1], n = 1
输出:true
输入:flowerbed = [1,0,0,0,1], n = 2
输出:false

方法

code

js

let canPlaceFlowers = (flowerbed, n) => {
    if (n < 0)
        return false;
    let cnt = 0;
    let len = flowerbed.length;
    for (let i = 0; i < len; i++) {
        if (flowerbed[i] === 1)
            continue;
        let pre = i === 0 ? 0 : flowerbed[i - 1];
        let next = i === len - 1 ? 0 : flowerbed[i + 1];
        if (pre === 0 && next === 0) {
            cnt++;
            flowerbed[i] = 1;
        }
    }
    return cnt >= n;
};
console.log(canPlaceFlowers([1,0,0,0,1], 1));
console.log(canPlaceFlowers([1,0,0,0,1], 2));

go

func canPlaceFlower(flowerbed []int, n int) bool {
	if n < 0 {
		return false
	}
	cnt := 0
	l := len(flowerbed)
	for i := 0; i < l; i++ {
		if flowerbed[i] == 1{
			continue
		}
		pre, next := 0, 0
		if i == 0 {
			pre = 0
		} else {
			pre = flowerbed[i - 1]
		}
		if i == l - 1 {
			next = 0
		} else {
			next = flowerbed[i + 1]
		}
		if pre == 0 && next == 0 {
			cnt++
			flowerbed[i] = 1
		}
	}
	return cnt >= n
}

java

class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        // 边界?
        if (n < 0) return false;
        int cnt = 0;
        int len = flowerbed.length;
        for (int i = 0; i < len; i++) {
            // 判断是1的
            if (flowerbed[i] == 1) continue;
            int pre = i == 0 ? 0 : flowerbed[i - 1];
            int next = i == len - 1 ? 0 : flowerbed[i + 1];
            if (pre == 0 && next == 0) {
                cnt++;
                flowerbed[i] = 1;
            }
        }
        return cnt >= n;
    }
}