【LeetCode】795. Number of Subarrays with Bounded Maximum 解题报告(Python & C++)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/description/
题目描述
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 L and 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两个数字。现在我们要求在这个数组中能有多少个连续的子数组,使得这个子数组的最大值在L和R之间。
解题方法
动态规划
第一感觉是dfs,但是看了下A的长度范围发现基本只能用O(n)的算法了,因此只能使用dp去求了。
我们设定dp数组,其dp[i]的含义是以A[i]为结尾的子数组中满足题目要求的数组个数。所以我们在这个定义的基础上,能得到下面的关系式:
- A[i] < L
这个情况,以A[i]为结尾的子数组的最大值没有改变,因此dp[i] = dp[i - 1] - A[i] > R
此时,以A[i]为结尾的子数组的最大值已经大于了R,所以dp[i] = 0.把这个位置设定为新的开始,记录该位置为prev. - L <= A[i] <= R
从prev到i之间的任意起始位置到i的子数组都满足题目条件,因此dp[i] = i - prev.
根据上面的关系式可以写出代码,最后的结果是整个dp之和。
该代码的时间复杂度是O(n),空间复杂度也是O(n)。
代码如下:
class Solution(object):
def numSubarrayBoundedMax(self, A, L, R):
"""
:type A: List[int]
:type L: int
:type R: int
:rtype: int
"""
if not A: return 0
dp = [0] * len(A)
prev = -1
for i, a in enumerate(A):
if a < L and i > 0:
dp[i] = dp[i - 1]
elif a > R:
dp[i] = 0
prev = i
elif L <= a <= R:
dp[i] = i - prev
return sum(dp)
因为dp[i]只和dp[i-1]有关,所以可以把空间复杂度将为O(1)。
class Solution(object):
def numSubarrayBoundedMax(self, A, L, R):
"""
:type A: List[int]
:type L: int
:type R: int
:rtype: int
"""
dp = 0
res = 0
prev = -1
for i, a in enumerate(A):
if a < L and i > 0:
res += dp
elif a > R:
dp = 0
prev = i
elif L <= a <= R:
dp = i - prev
res += dp
return res
暴力搜索+剪枝
如果二重循环可以求出每个数组,但是肯定会超时。不过,如果我们考虑一下剪枝,外层循环里面当前值大于R的时候,就移到下一个位置;内层循环里面,如果当前值大于R,那么后面的全部都不满足,所以直接break掉。这样就能过了!!
class Solution {
public:
int numSubarrayBoundedMax(vector<int>& A, int L, int R) {
const int N = A.size();
int res = 0;
for (int i = 0; i < N; ++i) {
if (A[i] > R) continue;
int curMax = INT_MIN;
for (int j = i; j < N; ++j) {
curMax = max(curMax, A[j]);
if (curMax > R) break;
if (curMax >= L) ++res;
}
}
return res;
}
};
线性遍历
定一个函数count():数组中最大值小于等于bound的子数组个数。所以,我们的最终结果是就是count - count(L-1)。
count函数很好设计,因为只需要线性遍历一次,就知道了。每次遍历的时候,如果当前的值小于等于bound,那么就等于在前面的子数组上又加上了一个新的数组。所以我们需要一个变量来保存前面的数组有多少个了。
class Solution {
public:
int numSubarrayBoundedMax(vector<int>& A, int L, int R) {
return count(A, R) - count(A, L - 1);
}
int count(vector<int>& A, int bound) {
int res = 0, cur = 0;
for (int x : A) {
cur = (x <= bound) ? cur + 1 : 0;
res += cur;
}
return res;
}
};
我最初的想法其实就是双指针,类似虫取法。虽然想法简单,但是如果思路不够清除,根本写不出来。下面就是这个虫取法求子数组的方法。
class Solution {
public:
int numSubarrayBoundedMax(vector<int>& A, int L, int R) {
const int N = A.size();
int res = 0;
int left = -1, right = -1;
for (int i = 0; i < N; ++i) {
if (A[i] > R) left = i;
if (A[i] >= L) right = i;
res += right - left;
}
return res;
}
};
参考资料:
http://www.cnblogs.com/grandyang/p/9237967.html
日期
2018 年 9 月 14 日 —— 现在需要的还是夯实基础,算法和理论
2018 年 12 月 16 日 —— 周赛好难
【LeetCode】795. Number of Subarrays with Bounded Maximum 解题报告(Python & C++)的更多相关文章
- LeetCode 795. Number of Subarrays with Bounded Maximum
问题链接 LeetCode 795 题目解析 给定一个数组A,左右范围L.R.求子数组的数量,要求:子数组最大值在L.R之间. 解题思路 子数组必须连续,利用最大值R对数组进行分段,设定变量 left ...
- 795. Number of Subarrays with Bounded Maximum
数学的方式 是对于所有的字符分成简单的三类 0 小于 L 1 LR 之间 2 大于R 也就是再求 不包含 2 但是包含1 的子数组个数 不包含2的子数组个数好求 对于连续的相邻的n个 非2类数 就有 ...
- [LeetCode] Number of Subarrays with Bounded Maximum 有界限最大值的子数组数量
We are given an array A of positive integers, and two positive integers L and R (L <= R). Return ...
- 74th LeetCode Weekly Contest Number of Subarrays with Bounded Maximum
We are given an array A of positive integers, and two positive integers L and R (L <= R). Return ...
- [Swift]LeetCode795. 区间子数组个数 | Number of Subarrays with Bounded Maximum
We are given an array A of positive integers, and two positive integers L and R (L <= R). Return ...
- LeetCode 806 Number of Lines To Write String 解题报告
题目要求 We are to write the letters of a given string S, from left to right into lines. Each line has m ...
- 【LeetCode】26. Remove Duplicates from Sorted Array 解题报告(Python&C++&Java)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 双指针 日期 [LeetCode] https:// ...
- 【LeetCode】450. Delete Node in a BST 解题报告 (Python&C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 迭代 日期 题目地址:https://leetcode ...
- 【LeetCode】452. Minimum Number of Arrows to Burst Balloons 解题报告(Python)
[LeetCode]452. Minimum Number of Arrows to Burst Balloons 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https ...
随机推荐
- vue-baidu-map相关随笔
一,使用vue-baidu-map 1.下载相关包依赖 npm i vue-baidu-map 2.在main.js中import引入相关包依赖,在main.js中添加如下代码: import B ...
- 大数据学习day21-----spark04------1. 广播变量 2. RDD中的cache 3.RDD的checkpoint方法 4. 计算学科最受欢迎老师TopN
1. 广播变量 1.1 补充知识(来源:https://blog.csdn.net/huashetianzu/article/details/7821674) 之所以存在reduce side jo ...
- 『学了就忘』Linux启动引导与修复 — 69、启动引导程序(grub)
目录 1.启动引导程序(Boot Loader)简介 2.启动引导程序grub的作用 3.启动引导程序grub的位置 4./grub目录中其他的文件简单介绍 提示: 简单地说,Boot Loader就 ...
- Shell学习(五)—— awk命令详解
一.awk简介 awk是一个非常好用的数据处理工具,相对于sed常常作用于一整个行的处理,awk则比较倾向于一行当中分成数个[字段]处理,因此,awk相当适合处理小型的数据数据处理.awk是一种报 ...
- oracle 当月日历的sql
select max(sun) sun, max(mon) mon, max(tue) tue, max(wed) wed, max(thu) thu, max(fri) fri, max(sat) ...
- Linux:sqlldr命令
第一步:写一个 ctl格式的控制文件 CTL 控制文件的内容 : load data --1. 控制文件标识 infile 'xxx.txt' --2. 要导入的数据文件名 insert into t ...
- redis入门到精通系列(六):redis的事务详解
(一)事务的概念 谈到数据库的高级应用,不可避免会谈到事务.熟悉mysql的朋友们对事务肯定不陌生,简单来讲事务就是控制一个数据库操作序列要么全部执行要么全部不执行.今天我们就来了解redis中的事务 ...
- GO类型转换
golang []byte转string golang中,字符切片[]byte转换成string最简单的方式是 package main import ( "fmt" _ &quo ...
- 基于war的Spring Boot工程
一.简介 前面创建的Spring Boot工程最终被打为了Jar包,是以可执行文件的形式出现的,其使用了Spring Boot内嵌的Tomcat作为Web服务器来运行web应用的.新版Dubbo的监控 ...
- 【Linux】【Services】【SaaS】Docker+kubernetes(9. 安装consul实现服务注册发现)
1. 简介 1.1. 官方网站: https://www.consul.io 1.2. Consul的功能: 服务发现:通过DNS或HTTP接口使得消费者发现服务,应用程序可以轻松找到所依赖的服务. ...