题解 | #最大放牛数#
最大放牛数
https://www.nowcoder.com/practice/5ccfbb41306c445fb3fd35a4d986f8b2?tpId=354&tqId=10595891&ru=/exam/oj&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Foj
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pasture int整型一维数组 * @param n int整型 * @return bool布尔型 */ public boolean canPlaceCows (int[] pasture, int n) { // write code here boolean[] flag = new boolean[pasture.length]; for (int i = 0; i < pasture.length; i++) { if (pasture[i] == 1) { flag[i] = true; if (i - 1 >= 0) { if (pasture[i - 1] != 1) { flag[i - 1] = true; } } if (i + 1 < pasture.length) { flag[i + 1] = true; } } } int res = 0; int count = 0; for (int i = 0; i < pasture.length; i++) { if (!flag[i]) { // 表示该位置可以放牛 count++; } else { // 该位置不可以放牛 res += (count + 1) / 2; count = 0; } } res += (count + 1) / 2; return res >= n; } }#数组计数##java##模拟#