Input: [1 10 6 7 9 8 2 4 3 5]
Output: How many people can the last one in line see?
Clarification:
- A person A can see another person B in front of them if there is no one taller than both A and B standing between them.
- Every person has a different height.
这道题要求统计队列最后一个人向前能看到多少人。关键在于“可见”的定义:如果两个人之间不存在一个比二者都高的人,那么前面的人就是可见的。由于每个人身高不同,可以从最后一个人往前扫描,维护当前见过的最高身高;当遇到一个比记录更高的人时,就说明他仍然可见并更新最高值。这个思路本质上是一次从右向左的线性遍历,时间复杂度为 O(n),适合用数组直接处理。
正文完