当前位置:   article > 正文

LeetCode 605. Can Place Flowers

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...

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/502220
推荐阅读
相关标签
  

闽ICP备14008679号