zoukankan      html  css  js  c++  java
  • LeetCode 795.区间子数组个数

    给定一个元素都是正整数的数组A ,正整数 L 以及 R (L <= R)。

    求连续、非空且其中最大元素满足大于等于L 小于等于R的子数组个数。

    例如 :
    输入:
    A = [2, 1, 4, 3]
    L = 2
    R = 3
    输出: 3
    解释: 满足条件的子数组: [2], [2, 1], [3].
    注意:

    L, R 和 A[i] 都是整数,范围在 [0, 10^9]。
    数组 A 的长度范围在[1, 50000]。

    ## 方法1、遍历法(剪枝)
    class Solution:
        def numSubarrayBoundedMax(self, A: List[int], L: int, R: int) -> int:
            ans = 0
            for start in range(len(A)):
                if A[start]>R:
                    continue
                cur_max = A[start]
                for end in range(start,len(A)):
                    cur_max = max(cur_max, A[end])
                    if cur_max > R:
                        break
                    if cur_max >= L:
                        ans += 1
            return ans
    
    ## 方法2、
    ## 最大值为R的子集的个数 - 最大值为L-1的子集个数
    class Solution:
        def numSubarrayBoundedMax(self, A: List[int], L: int, R: int) -> int:
           def helper(A,max_value):
                ans = 0
                cur_ans = 0
                for i in range(len(A)):
                    if A[i] <= max_value:
                        cur_ans+=1
                        ans+=cur_ans
                    else:
                        cur_ans = 0
                return ans
            return helper(A, R) - helper(A, L-1)
    
  • 相关阅读:
    STM32概述
    对xlslib库与libxls库的简易封装
    Makefile.am编写规则
    linux下使用autoconf制作Makefile
    python 登录三次禁止登录
    Linux -- gpasswd
    Linux -- userdel
    Linux -- groupmod
    Linux -- groupadd
    Linux -- passwd
  • 原文地址:https://www.cnblogs.com/sandy-t/p/13189467.html
Copyright © 2011-2022 走看看