每日刷题:605. 种花问题

235 阅读1分钟

605. 种花问题(难度:简单)

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

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

解题思路

  1. 找到第一个花的位置,接着找到下一个花的位置;
  2. 查找两朵花之间可种植的最大数量;
  3. 花坛第一朵花之前以及花坛最后一堆花之后也需要计算可种植的最大数量;

题解

public boolean canPlaceFlowers(int[] flowerbed, int n) {
   int canBePlantedCount = 0;
   int prevIndex = -1;
   int flowerbedSize = flowerbed.length;

   for (int index = 0; index < flowerbedSize; index++) {
       if (flowerbed[index] == 0) continue;

       if (prevIndex < 0) {
           canBePlantedCount += index / 2;
       } else {
           int betweenSize = index - prevIndex - 1;
           canBePlantedCount += Math.abs(betweenSize - 1) / 2;
       }

       if (canBePlantedCount >= n) {
           return true;
       }

       prevIndex = index;
   }

   if (prevIndex < 0) {
       canBePlantedCount += (flowerbedSize + 1) / 2;
   } else {
       canBePlantedCount += (flowerbedSize - 1 - prevIndex) / 2;
   }
   return canBePlantedCount >= n;
}

测试

CanPlaceFlowers canPlaceFlowers = new CanPlaceFlowers();

@Test
public void test_case1() {
    int[] flowerbed = new int[]{1, 0, 0, 0, 1};
    Assertions.assertTrue(canPlaceFlowers.canPlaceFlowers(flowerbed, 1));
}

@Test
public void test_case2() {
    int[] flowerbed = new int[]{1, 0, 0, 0, 1};
    Assertions.assertFalse(canPlaceFlowers.canPlaceFlowers(flowerbed, 2));
}

@Test
public void test_case3() {
    int[] flowerbed = new int[]{0, 0, 0, 0};
    Assertions.assertTrue(canPlaceFlowers.canPlaceFlowers(flowerbed, 2));
}

@Test
public void test_case4() {
    int[] flowerbed = new int[]{0, 0, 0, 0, 0};
    Assertions.assertTrue(canPlaceFlowers.canPlaceFlowers(flowerbed, 3));
}

    @Test
public void test_case5() {
    int[] flowerbed = new int[]{1, 0, 0, 1};
    Assertions.assertFalse(canPlaceFlowers.canPlaceFlowers(flowerbed, 1));
}

@Test
public void test_case6() {
    int[] flowerbed = new int[]{1, 0, 1, 0};
    Assertions.assertFalse(canPlaceFlowers.canPlaceFlowers(flowerbed, 1));
}

@Test
public void test_case7() {
    int[] flowerbed = new int[]{1, 0, 0, 0, 0, 0, 1};
    Assertions.assertTrue(canPlaceFlowers.canPlaceFlowers(flowerbed, 2));
}

@Test
public void test_case8() {
    int[] flowerbed = new int[]{1, 0, 1, 0, 1, 0, 1};
    Assertions.assertFalse(canPlaceFlowers.canPlaceFlowers(flowerbed, 1));
}

@Test
public void test_case9() {
    int[] flowerbed = new int[]{0, 0, 1, 0, 1};
    Assertions.assertTrue(canPlaceFlowers.canPlaceFlowers(flowerbed, 1));
}

@Test
public void test_case10() {
    int[] flowerbed = new int[]{1, 0, 0, 0, 1, 0, 0};
    Assertions.assertTrue(canPlaceFlowers.canPlaceFlowers(flowerbed, 2));
}