给定一个元素都是正整数的数组A ,正整数 L 以及 R (L <= R)。
求连续、非空且其中最大元素满足大于等于L 小于等于R的子数组个数。
例如 :
输入:
A = [2, 1, 4, 3]
L = 2
R = 3
输出: 3
解释: 满足条件的子数组: [2], [2, 1], [3].
链接:https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/
解题思路:双指针法
class Solution(object):
def numSubarrayBoundedMax(self, A, L, R):
"""
:type A: List[int]
:type L: int
:type R: int
:rtype: int
"""
# 优化
start = end = -1
res = 0
for i in range(len(A)):
if A[i] > R:
start = i
if A[i] >= L:
end = i
res += end - start
return res
# # 双指针法
# start = -1
# end = 0
# l = len(A)
# res = 0
# cur = -1
# while end < l:
# if L <= A[end] <= R:
# res += end - start
# cur = end
# elif A[end] > R:
# start = end
# cur = end
# elif A[end] < L and cur != -1:
# res += cur - start
# end += 1
# return res
Time:O(N)
Space: O(1)
难度:中等