classSolution: defcountSubarrays(self, nums: List[int], min_k: int, max_k: int) -> int: ans = 0 min_i = max_i = i0 = -1 for i, x inenumerate(nums): if x == min_k: min_i = i if x == max_k: max_i = i ifnot min_k <= x <= max_k: i0 = i # 子数组不能包含 nums[i0] ans += max(min(min_i, max_i) - i0, 0) # 注:上面这行代码,改为手动算 min max 会更快 # j = min_i if min_i < max_i else max_i # if j > i0: ans += j - i0 return ans
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution { publiclongcountSubarrays(int[] nums, int minK, int maxK) { varans=0L; intn= nums.length, minI = -1, maxI = -1, i0 = -1; for (vari=0; i < n; ++i) { varx= nums[i]; if (x == minK) minI = i; if (x == maxK) maxI = i; if (x < minK || x > maxK) i0 = i; // 子数组不能包含 nums[i0] ans += Math.max(Math.min(minI, maxI) - i0, 0); } return ans; } }
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { public: longlongcountSubarrays(vector<int> &nums, int min_k, int max_k){ longlong ans = 0L; int n = nums.size(), min_i = -1, max_i = -1, i0 = -1; for (int i = 0; i < n; ++i) { int x = nums[i]; if (x == min_k) min_i = i; if (x == max_k) max_i = i; if (x < min_k || x > max_k) i0 = i; // 子数组不能包含 nums[i0] ans += max(min(min_i, max_i) - i0, 0); } return ans; } };
[sol1-Go]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
funccountSubarrays(nums []int, minK, maxK int) (ans int64) { minI, maxI, i0 := -1, -1, -1 for i, x := range nums { if x == minK { minI = i } if x == maxK { maxI = i } if x < minK || x > maxK { i0 = i // 子数组不能包含 nums[i0] } ans += int64(max(min(minI, maxI)-i0, 0)) } return }
funcmin(a, b int)int { if b < a { return b }; return a } funcmax(a, b int)int { if b > a { return b }; return a }