知识点:数组
可放置的要求是左右相邻的元素都为0,我们只需要遍历一遍数组,同时进行判断,若左右元素不为1,则将当前位置置1,同时n-1,表示已放置,继续向后遍历,遍历完成整个数组后,若n<=0,则说明有多于n个位置可放置,返回true。
Java题解如下
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pasture int整型一维数组
* @param n int整型
* @return bool布尔型
*/
public boolean canPlaceCows (int[] pasture, int n) {
// write code here
int len = pasture.length;
for(int i = 0; i < len; i++) {
if(i > 0 && pasture[i - 1] == 1) {
continue;
}
if(i < len - 1 && pasture[i + 1] == 1) {
continue;
}
pasture[i] = 1;
i++;
n--;
}
return n <= 0;
}
}



京公网安备 11010502036488号