74th LeetCode Weekly Contest Number of Subarrays with Bounded Maximum

2018/03/06 19:21
阅读数 17

We are given an array A of positive integers, and two positive integers L and R (L <= R).

Return the number of (contiguous, non-empty) subarrays such that the value of the maximum array element in that subarray is at least Land at most R.

Example :
Input: 
A = [2, 1, 4, 3]
L = 2
R = 3
Output: 3
Explanation: There are three subarrays that meet the requirements: [2], [2, 1], [3].

Note:

  • L, R  and A[i] will be an integer in the range [0, 10^9].
  • The length of A will be in the range of [1, 50000].

有多少连续的子数组,必须存在[L,R],但不能超过R

应该知道了,A[i]在L,R之间是num+=(i-j),超过R需要记录j=i,但如何处理小于L的数字

因为必须存在[L,R],单纯的小于L不能算,那么就拿一个k记录一下不在[L,R]的位置,然后(i-j)-(i-k+1)就好了

 1 class Solution {
 2 public:
 3     int numSubarrayBoundedMax(vector<int>& A, int L, int R) {
 4             int aLen=A.size();
 5             int num=0;
 6             int k=0;
 7             int i=0,j=-1;
 8             for(int i=0;i<aLen;i++){
 9                 if(A[i]>R){
10                     k=i+1;
11                     j=i;
12                 }else if(A[i]<L){
13                     num+=(i-j)-(i-k+1);
14                 }else{
15                     num+=(i-j);
16                     k=i+1;
17                 }
18             }
19             return num;
20     }
21 };

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部