题解 | #牛群的可视高度#
牛群的可视高度
https://www.nowcoder.com/practice/942d0585a5654dbb9d5000feaa4e177e
题目考察的知识点是:
贪心算法。
题目解答方法的文字分析:
我们从左到右遍历数组,并维护一个最高值,如果当前值比最大值大,那么可见的牛数+1且更新最大值的值。
本题解析所用的编程语言:
java语言。
完整且正确的编程代码:
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param cowHeights int整型一维数组 * @return int整型 */ public int visibleCows (int[] cowHeights) { // write code here int max = -1, sum = 0; for (int i = 0; i < cowHeights.length; i++) { if (max < cowHeights[i]) { max = cowHeights[i]; sum++; } } return sum; } }#题解#