• LeetCode 605. 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 <= flowerbed.length <= 2 * 104
    • flowerbed[i] is 0 or 1.
    • There are no two adjacent flowers in flowerbed.
    • 0 <= n <= flowerbed.length

    给了一个0和1构成的数组,要把其中的0变成1,使得最后形成的数组不能有相邻的1。这题刚开始的直观思路就是那就从最左开始放1,能尽量往左放就放,就是greedy的思想,但是并不会证明它的正确性。看了答案确实它是正确的……于是就写了代码,嗯,刚开始还被坑了一下,如果n为0的时候我这个会返回false,看了答案最后是返回count >= n,倒也合理。

    Runtime: 1 ms, faster than 100.00% of Java online submissions for Can Place Flowers.

    Memory Usage: 52 MB, less than 63.67% of Java online submissions for Can Place Flowers.

    1. class Solution {
    2. public boolean canPlaceFlowers(int[] flowerbed, int n) {
    3. if (n == 0) {
    4. return true;
    5. }
    6. int count = 0;
    7. for (int i = 0; i < flowerbed.length; i++) {
    8. if (flowerbed[i] == 0) {
    9. boolean emptyLeft = (i == 0) || (flowerbed[i - 1] == 0);
    10. boolean emptyRight = (i == flowerbed.length - 1) || (flowerbed[i + 1]) == 0;
    11. if (emptyLeft && emptyRight) {
    12. flowerbed[i] = 1;
    13. count++;
    14. if (count == n) {
    15. return true;
    16. }
    17. }
    18. }
    19. }
    20. return false;
    21. }
    22. }

    还看到有人提到说上面这个做法改变了input array, which is not a good idea,确实。如果需要保持原来的array,我们需要额外定义一个变量来存放前一个1的位置。以及如果这道题是求一共有多少种方法来实现,那么应该用dp,嗯,懒得想了,以后有空回来填坑好了。

    还有一种思路是通过连续的0的个数来算,假如两个1之间有n个0,那么这些0之中可以有(n - 1) / 2个0变成1。比如(0, 0) -> 0,(0, 0, 0) - > 1,(0, 0, 0, 0) -> 1……前面这里没有考虑到第一个或者最后一个为0的情况,于是还需要额外在原数组前后加一个dummy 0,因此可以最开始的时候把0的个数初始化为1,最后return的时候因为return的要是最后一串0,又因为多一个dummy 0,所以最后result + n / 2就是最终可以放下的数量。代码就不写了,贴链接吧。

    Loading...

  • 相关阅读:
    Java新特性(2):Java 10以后
    【C++】多态 ⑫ ( 多继承 “ 弊端 “ | 多继承被禁用的场景 | 菱形继承结构的二义性 | 使用虚继承解决菱形继承结构的二义性 )
    pytorch异常——loss异常,不断增大,并且loss出现inf
    低代码+流程管理,打造信息工程项目动态管理系统
    css实现滚动视差效果
    【CQF Finance Class 1 现金时间价值】
    Go_原子操作和锁
    第五章:最新版零基础学习 PYTHON 教程—Python 字符串操作指南(第七节 - Python 中使用 % 进行字符串格式化)
    linux操作系统中业务程序及服务的开机启动
    C语言进阶——文件操作
  • 原文地址:https://blog.csdn.net/qq_37333947/article/details/127673559