美文网首页
算法5 种花

算法5 种花

作者: holmes000 | 来源:发表于2017-09-17 21:51 被阅读0次

    题目:假设你有一个长的多块花坛,其中一些地块种植花,有些不种。条件是花不能种植在相邻的地块 - 他们会争取水,两者都会死亡。
    给定一个花坛(表示为包含0和1的数组,其中0表示空白,1表示不为空),给出想要新增n个地块种花,如果n个地块可以种植在其中,而不违反不相邻花规则,则返回ture,否则false。
    思路:
    假设花坛有是int a = [1,0,0,0,1]则a[2]可以种 1,n为1时返回true,其它false。
    考虑这块地的左右是否种了花
    代码

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

    相关文章

      网友评论

          本文标题:算法5 种花

          本文链接:https://www.haomeiwen.com/subject/kzimsxtx.html