【前缀和 + 哈希】把小于k的当做-1,大于k的当做1,那么通过前缀和计算出的一段区间内得分为0或者1就说明符合要求。
class Solution {
public int countSubarrays(int[] nums, int k) {
int n = nums.length, idx = 0, ans = 0;
int[] s = new int[n + 1];
for (int i = 1; i <= n; i++) s[i] = s[i - 1] + (nums[i - 1] > k ? 1: (nums[i - 1] == k? 0: -1));
Map<Integer, Integer> map = new HashMap();
map.put(0, 1);
for (int i = 0; i < n; i++) {
if (nums[i] == k) {
idx = i + 1;
break;
}
}
for (int i = 1; i <= n; i++) {
if (i < idx) map.put(s[i], map.getOrDefault(s[i], 0) + 1);
else {
ans += map.getOrDefault(s[i], 0) + map.getOrDefault(s[i] - 1, 0);
}
}
return ans;
}
}