题解 | #牛群的可视高度#
牛群的可视高度
https://www.nowcoder.com/practice/942d0585a5654dbb9d5000feaa4e177e
知识点:贪心
顺序遍历数组,不停寻找最大值,当找到最大值,表示在左视图时可以看到该元素,计数加一,遍历整个数组,最终计数即为左视图可以看到的元素个数。
Java题解如下
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param cowHeights int整型一维数组
* @return int整型
*/
public int visibleCows (int[] cowHeights) {
// write code here
int cnt = 0;
int max = 0;
for(int h: cowHeights) {
if(h > max) {
max = h;
cnt++;
}
}
return cnt;
}
}

查看26道真题和解析