【LeetCode】数组-3(605)-种花问题( 1 的两侧不能有 1 )

开始的思路:首先统计需要种几只花,用花的数目统计连续 0 的个数.... ...【囧】突然觉得情况有点复杂啊,有连续的又有分散的怎么能统计全呢?

好吧这里喔偷偷的瞄了一眼参看答案... ...(就一眼就想通了)

思路一:

简单扫描统计,一个一个遍历,遍历到 i 的时候, i 前后的位置也要等于 0;

特殊情况 首尾有连续两个 0 的情况----首尾又可以种花了【笑脸】

程序中需要注意的点:

1. 满足条件的要放上 1;

2. 为防止下标越界,i+1 位的判断应该放到 || “短路或”的右边, i-1 位的判断应该放到 || “短路或”的左边。

【正确的代码】

 public class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
int i = 0;
int count = 0;
while (i < flowerbed.length) {
if ((flowerbed[i] == 0) && (i == flowerbed.length - 1 || flowerbed[i + 1] == 0) && (i == 0 || flowerbed[i - 1] == 0)) {
// i 没在头尾:需要判断 i-1 和 i+1 位置是不是0;i 在头,则 i+1 为 0 可以放一个; i 在尾,在 i-1 为 0 可以放一个
flowerbed[i] = 1;
count++;
}
i++;
}
if (count >= n) {
return true;
}
return false;
}
}

复杂度分析:

时间复杂度:O(n) 全遍历一遍

空间复杂度:O(1)

思路一的优化:

上面的count统计的是最多能种花的数量,如果n的值很小,则统计最多的数量就有些浪费了,所以我们可以把count和n的比较放到循环中进行,一旦count > n 就立即return true 减少计算量。

【正确的代码】

 public class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
int i = 0;
int count = 0;
while (i < flowerbed.length) {
if ((flowerbed[i] == 0) && (i == flowerbed.length - 1 || flowerbed[i + 1] == 0) && (i == 0 || flowerbed[i - 1] == 0)) {
flowerbed[i] = 1;
count++;
}
if (count >= n)
return true;
i++;
}
return false;
}
}

复杂度分析:

时间复杂度:O(n) 最坏的情况是全遍历一遍

空间复杂度:O(1)

上一篇:Domino 邮箱服务器接收不存在的邮箱账号的邮件


下一篇:ci框架nginx访问