原题链接在这里:https://leetcode.com/problems/count-subarrays-with-fixed-bounds/

题目:

You are given an integer array nums and two integers minK and maxK.

A fixed-bound subarray of nums is a subarray that satisfies the following conditions:

  • The minimum value in the subarray is equal to minK.
  • The maximum value in the subarray is equal to maxK.

Return the number of fixed-bound subarrays.

A subarray is a contiguous part of an array.

Example 1:

Input: nums = [1,3,5,2,7,5], minK = 1, maxK = 5
Output: 2
Explanation: The fixed-bound subarrays are [1,3,5] and [1,3,5,2].

Example 2:

Input: nums = [1,1,1,1], minK = 1, maxK = 1
Output: 10
Explanation: Every subarray of nums is a fixed-bound subarray. There are 10 possible subarrays.

Constraints:

  • 2 <= nums.length <= 105
  • 1 <= nums[i], minK, maxK <= 106

题解:

For valid subarray, it must have both minK and maxK.

When iterate nums[i], it is out of [minK, maxK], we need to set the start of subarray as i + 1.

When we see minK and maxK, update last seen index for minK and maxK.

The start of subarray could be choosen from j to min(lastMinInd, lastMaxInd). 

e.g. [1, 3, 5, 1, 7, 5]. minK = 1, maxK = 5.

When ind = 3, num = 1. start of subarray could be 1, 3, 5. The corresponding subarray is [1, 3, 5, 1], [3, 5, 1] and [5, 1].

Time Complexity: O(n). n = nums.length.

Space: O(1).

AC Java:

 1 class Solution {
 2     public long countSubarrays(int[] nums, int minK, int maxK) {
 3         int n = nums.length;
 4         int startInd = 0;
 5         int lastMinInd = -1;
 6         int lastMaxInd = -1;
 7         long res = 0;
 8         for(int i = 0; i < n; i++){
 9             if(nums[i] < minK || nums[i] > maxK){
10                 lastMinInd = lastMaxInd = -1;
11                 startInd = i + 1;
12             }
13             
14             if(nums[i] == minK){
15                 lastMinInd = i;
16             }
17             
18             if(nums[i] == maxK){
19                 lastMaxInd = i;
20             }
21             
22             res += Math.max(0L, Math.min(lastMinInd, lastMaxInd) - startInd + 1);
23         }
24         
25         return res;
26     }
27 }

类似Number of Subarrays with Bounded Maximum.

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/16796157.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性