题解 | #牛群的可视高度# java
牛群的可视高度
https://www.nowcoder.com/practice/942d0585a5654dbb9d5000feaa4e177e
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param cowHeights int整型一维数组 * @return int整型 */ public int visibleCows (int[] cowHeights) { // write code here int visibleCount = 0; // 记录能看到的牛的数量 int maxHeight = 0; // 当前能看到的最高牛的高度 for (int height : cowHeights) { if (height > maxHeight) { visibleCount++; maxHeight = height; // 更新当前能看到的最高牛的高度 } } return visibleCount; } }
Java 编程语言。
该题考察了以下知识点:
- 数组遍历
- 条件判断
代码的文字解释如下:
- 创建两个变量:
visibleCount
用于记录能看到的牛的数量,maxHeight
用于记录当前能看到的最高牛的高度。 - 遍历给定的
cowHeights
数组中的每个元素height
。 - 对于每个牛的高度,如果它的高度大于当前能看到的最高牛的高度
maxHeight
,则说明我们能够看到这头牛,因此将visibleCount
增加 1,并更新maxHeight
为当前牛的高度。 - 返回
visibleCount
,即从左到右能够看到的牛的数量。