import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param pasture int整型一维数组
     * @param n int整型
     * @return bool布尔型
     */
    public boolean canPlaceCows (int[] pasture, int n) {
        // write code here
        Stack<Integer> stack = new Stack<>();  
        int index = 0;
        if (pasture[0] == 0 && pasture[1] == 0) {
            stack.add(1);
            index++;
        } else {
            stack.add(pasture[0]);
        }
      
        for (int i = 1; i < pasture.length; i++) {
            if (pasture[i] == 1) {
                stack.add(pasture[i]);
            } else if (pasture[i] == 0) {
                if (stack.peek() == 0) {
                    stack.add(1);
                    index++;
                } else {
                    stack.add(pasture[i]);
                }
            }
        }
        return index >= n;
    }

}

本题考察的知识点是数组元素的插入,所用编程语言是java。

对于这题我们需要明白什么位置可以插入,什么位置不可以插入