java 数组面试 3

一到简单有趣的面试题:

Suppose 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 - they would compete for water and both would die.

Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a number n, return if n new flowers can be planted in it 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

Note:

  1. The input array won't violate no-adjacent-flowers rule.
  2. The input array size is in the range of [1, 20000].
  3. n is a non-negative integer which won't exceed the input array size.

种花问题:

给你一个数组,里面只有数字0和1,0代表空地,1代表花,为了避免争抢资源,规定:不能由两朵花种在相邻的位置上,距离【1,0,1,0,1】是符合要求的,而【1,1,0,1,0】是不符合要求的,因为这个数组的前两位都是有花种在上面,违反了我们的规则,函数还有一个输入项,n, 如果数组中可以种花的空地>=n,则返回true,否则,返回false。

解题思路:

我们考虑在什么情况下可以种花

1:如果数组中出现了【0,0,0】的时候,我们知道,我们可以在中间种花

2:在数组的开头和结尾,需要特殊的考虑,如果数组开头或结尾是【0,0】,则我们可以在开头或结尾种花

代码如下:

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

Big O: O(n)

这道题解题思路清晰,你只需要遍历整个数组,找到【0,0,0】的个数,并在中间种花,然后对开头和结尾做一下特殊考虑即可

你可能感兴趣的:(java 数组面试 3)