33. Leaders of the Pack
Runners cross a finish line one after another, and the array nums lists each runner's speed reading in the order they crossed. A runner is called a leader if their reading is strictly greater than every reading of the runners who crossed after them. The very last runner has nobody after them, so they are always a leader.
Write a method findLeaders that takes the array nums and returns all the leaders' readings, in the same left-to-right order in which they appear in nums.
Example 1
- Input:
- nums = [16,17,4,3,5,2]
- Output:
- [17,5,2]
- Explanation:
17 is greater than everything after it, 5 is greater than the 2 after it, and 2 is last. So the leaders are [17, 5, 2].
Example 2
- Input:
- nums = [1,2,3,4,5]
- Output:
- [5]
- Explanation:
Each reading is followed by something larger, except the last one, so only 5 is a leader.
Constraints
1 ≤ nums.length ≤ 1000
-109 ≤ nums[i] ≤ 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(n)