C#LeetCode刷题之#605-种花问题( Can Place Flowers)

时间:2023-03-10 03:12:21
C#LeetCode刷题之#605-种花问题( Can Place Flowers)

问题

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3724 访问。

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

给定一个花坛(表示为一个数组包含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

注意:

数组内已种好的花不会违反种植规则。

输入的数组长度范围为 [1, 20000]。

n 是非负整数,且不会超过输入数组的大小。


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.

Input: flowerbed = [1,0,0,0,1], n = 1

Output: True

Input: flowerbed = [1,0,0,0,1], n = 2

Output: False

Note:

The input array won't violate no-adjacent-flowers rule.

The input array size is in the range of [1, 20000].

n is a non-negative integer which won't exceed the input array size.


示例

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3724 访问。

public class Program {

    public static void Main(string[] args) {
int[] nums = null; nums = new int[] { 1, 0, 0, 0, 1 };
var res = CanPlaceFlowers(nums, 1);
Console.WriteLine(res); Console.ReadKey();
} private static bool CanPlaceFlowers(int[] flowerbed, int n) {
//该题比较简单,处理好边界即可
//需要种植的花为0,总是可以
if(n == 0) return true;
//数组为0,不可种植
if(flowerbed.Length == 0) {
return false;
}
//当数组为1时,根据是否种植直接判定即可
if(flowerbed.Length == 1) {
if(flowerbed[0] == 0) {
return true;
} else {
return false;
}
}
//记录可以种植的数量
int count = 0;
//前2个分析
if(flowerbed.Length >= 2 &&
flowerbed[0] == 0 &&
flowerbed[1] == 0) {
flowerbed[0] = 1;
count++;
}
//连续3个为0时,可种植
for(int i = 1; i < flowerbed.Length - 1; i++) {
if(flowerbed[i - 1] == 0 &&
flowerbed[i] == 0 &&
flowerbed[i + 1] == 0) {
count++;
flowerbed[i] = 1;
}
}
//后2个分析
if(flowerbed.Length >= 2 &&
flowerbed[flowerbed.Length - 1] == 0 &&
flowerbed[flowerbed.Length - 2] == 0) {
flowerbed[flowerbed.Length - 1] = 1;
count++;
}
//可种植数大于等于即将种植的数量时,返回true
if(count >= n) return true;
//无解时,返回false
return false;
} }

以上给出1种算法实现,以下是这个案例的输出结果:

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3724 访问。

True

分析:

该题比较简单,若使用其它ADT,可以考虑左右边界补0的方法,这样可以少处理部分边界问题。

显而易见,以上算法的时间复杂度为: C#LeetCode刷题之#605-种花问题( Can Place Flowers) 。