解题思路
本题中的子数组,称为递增子数组。
子数组指的是一个数组中一段连续的数组序列。
假设nums的长度为n,则nums的子数组的个数为
n
×
(
n
+
1
)
2
\frac{n\times(n+1)}{2}
2n×(n+1)。
因此只需要找出不满足的递增子数组即可。
python
class Solution:
def incremovableSubarrayCount(self, nums: List[int]) -> int:
n = len(nums)
res = 0
for i in range(n):
for j in range(i, n):
num = nums[:i] + nums[j+1:]
if self.isIncrement(num):
res +=1
return res
def isIncrement(self, nums):
for i in range(1,len(nums)):
if nums[i] <= nums[i-1]:
return False
return True
实际上就是假设找到了移除递增子数组,则子数组的左边严格递增,右边也是严格递增,同样nums[l] > nums[r+1]。可以进一步简写得到:
class Solution:
def incremovableSubarrayCount(self, nums: List[int]) -> int:
n = len(nums)
return sum([self.isIncreasing(nums[:i] + nums[j+1:]) for i in range(n) for j in range(i, n)])
def isIncreasing(self, nums):
# 判断是否严格递增的
if len(nums) == 0:
return True
return all(nums[i] < nums[i+1] for i in range(len(nums) - 1))
C++
c++不像python一样可以对列表直接截取,因此判断时传入i,j进行判断即可。
class Solution {
public:
int incremovableSubarrayCount(vector<int>& nums) {
int n = nums.size();
int res = 0;
for (int i = 0; i < n; i++){
for (int j = i; j < n; j++){
if (isIncreasing(nums, i, j)){
res ++;
}
}
}
return res;
}
bool isIncreasing(vector<int>& nums, int l, int r){
for (int i = 1; i < nums.size(); i++){
// 处于l,r区间内
if (i >=l && i <= r+1) continue;
if (nums[i] <= nums[i-1]) return false;
}
// 再判断一下左右两边是否满足递增
if (l-1 >= 0 && r+1 < nums.size() && nums[r+1] <=nums[l-1]) return false;
return true;
}
};
java
class Solution {
public int incremovableSubarrayCount(int[] nums) {
int n = nums.length;
int res = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
if (isIncreasing(nums, i, j)) {
res++;
}
}
}
return res;
}
public boolean isIncreasing(int[] nums, int l, int r) {
for (int i = 1; i < nums.length; i++) {
if (i >= l && i <= r + 1) {
continue;
}
if (nums[i] <= nums[i - 1]) {
return false;
}
}
if (l - 1 >= 0 && r + 1 < nums.length && nums[r + 1] <= nums[l - 1]) {
return false;
}
return true;
}
}