原题说明
Given an array A
of integers, return the number of non-empty continuous subarrays that satisfy the following condition:
The leftmost element of the subarray is not larger than other elements in the subarray.
Example 1:
Input: [1,4,2,5,3]
Output: 11
Explanation: There are 11 valid subarrays: [1],[4],[2],[5],[3],[1,4],[2,5],[1,4,2],[2,5,3],[1,4,2,5],[1,4,2,5,3].
Example 2:
Input: [3,2,1]
Output: 3
Explanation: The 3 valid subarrays are: [3],[2],[1].
Example 3:
Input: [2,2,2]
Output: 6
Explanation: There are 6 valid subarrays: [2],[2],[2],[2,2],[2,2],[2,2,2].
Note:
1 <= A.length <= 50000
0 <= A[i] <= 100000
解题思路
建立一个从顶往下递减的栈stk
,遍历nums
中每个元素num
,比较num
与栈顶元素大小。
如果num
较大,则不断pop
栈顶元素,直到栈空或者栈顶元素小于等于num
,然后将num
插入栈顶。
此时,我们可以以stk
中任意元素为开头,以num
为结尾组成符合题目条件的subarray,因此
以num
为结尾的subarray个数为stk
的size
。
示例代码 (cpp)
1 | class Solution { |
示例代码 (java)
1 | class Solution { |
示例代码 (python)
1 | class Solution: |
复杂度分析
时间复杂度: O(N)
空间复杂度: O(N)
视频讲解
我们在Youtube上更新了视频讲解,欢迎关注!