题解 | #最大放牛数#
最大放牛数
https://www.nowcoder.com/practice/5ccfbb41306c445fb3fd35a4d986f8b2
- 题目考察的知识点 : 贪心算法
- 题目解答方法的文字分析:
- 如果 pasture[i] 和 pasture[i+1] 都是 0,那么就可以在这两个位置上分别放置一头牛。然后再继续向后遍历 pasture 数组,重复以上操作,直到不能再放置更多的牛为止
- 如果 pasture 数组中所有值的和都小于等于 n,那么一定可以将 n 头牛放到 pasture 中,此时应该返回 true。
- 在遍历 pasture 数组时,最后一个位置不能再放置牛,因为它没有右侧相邻的位置。
- 在遍历 pasture 数组时,我们需要跳过已经放置了牛的位置,否则会引发争斗。
- 本题解析所用的编程语言: Python
- 完整且正确的编程代码
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param pasture int整型一维数组 # @param n int整型 # @return bool布尔型 # class Solution: def canPlaceCows(self , pasture: List[int], n: int) -> bool: count = sum(pasture) if count <= n: return True i = 0 while i < len(pasture) - 1: if pasture[i] == 0 and pasture[i+1] == 0: n -= 1 pasture[i] = 1 i += 1 if n == 0: return True return False
牛客高频top202题解系列 文章被收录于专栏
记录刷牛客高频202题的解法思路