comments | difficulty | edit_url | rating | source | tags | |||
---|---|---|---|---|---|---|---|---|
true |
困难 |
1998 |
第 321 场周赛 Q4 |
|
给你一个长度为 n
的数组 nums
,该数组由从 1
到 n
的 不同 整数组成。另给你一个正整数 k
。
统计并返回 nums
中的 中位数 等于 k
的非空子数组的数目。
注意:
- 数组的中位数是按 递增 顺序排列后位于 中间 的那个元素,如果数组长度为偶数,则中位数是位于中间靠 左 的那个元素。
<ul> <li>例如,<code>[2,3,1,4]</code> 的中位数是 <code>2</code> ,<code>[8,4,3,5,1]</code> 的中位数是 <code>4</code> 。</li> </ul> </li> <li>子数组是数组中的一个连续部分。</li>
示例 1:
输入:nums = [3,2,1,4,5], k = 4 输出:3 解释:中位数等于 4 的子数组有:[4]、[4,5] 和 [1,4,5] 。
示例 2:
输入:nums = [2,3,1], k = 3 输出:1 解释:[3] 是唯一一个中位数等于 3 的子数组。
提示:
n == nums.length
1 <= n <= 105
1 <= nums[i], k <= n
nums
中的整数互不相同
我们先找到中位数
定义一个答案变量
接下来,从
同理,从
最后,返回答案变量
时间复杂度
在编码上,我们可以直接开一个长度为
$2 \times n + 1$ 的数组,用于统计当前数组中,比$k$ 大的元素的个数与比$k$ 小的元素的个数的差值,每一次我们将差值加上$n$ ,即可将差值的范围从$[-n, n]$ 转换为$[0, 2n]$ 。
class Solution:
def countSubarrays(self, nums: List[int], k: int) -> int:
i = nums.index(k)
cnt = Counter()
ans = 1
x = 0
for v in nums[i + 1 :]:
x += 1 if v > k else -1
ans += 0 <= x <= 1
cnt[x] += 1
x = 0
for j in range(i - 1, -1, -1):
x += 1 if nums[j] > k else -1
ans += 0 <= x <= 1
ans += cnt[-x] + cnt[-x + 1]
return ans
class Solution {
public int countSubarrays(int[] nums, int k) {
int n = nums.length;
int i = 0;
for (; nums[i] != k; ++i) {
}
int[] cnt = new int[n << 1 | 1];
int ans = 1;
int x = 0;
for (int j = i + 1; j < n; ++j) {
x += nums[j] > k ? 1 : -1;
if (x >= 0 && x <= 1) {
++ans;
}
++cnt[x + n];
}
x = 0;
for (int j = i - 1; j >= 0; --j) {
x += nums[j] > k ? 1 : -1;
if (x >= 0 && x <= 1) {
++ans;
}
ans += cnt[-x + n] + cnt[-x + 1 + n];
}
return ans;
}
}
class Solution {
public:
int countSubarrays(vector<int>& nums, int k) {
int n = nums.size();
int i = find(nums.begin(), nums.end(), k) - nums.begin();
int cnt[n << 1 | 1];
memset(cnt, 0, sizeof(cnt));
int ans = 1;
int x = 0;
for (int j = i + 1; j < n; ++j) {
x += nums[j] > k ? 1 : -1;
if (x >= 0 && x <= 1) {
++ans;
}
++cnt[x + n];
}
x = 0;
for (int j = i - 1; ~j; --j) {
x += nums[j] > k ? 1 : -1;
if (x >= 0 && x <= 1) {
++ans;
}
ans += cnt[-x + n] + cnt[-x + 1 + n];
}
return ans;
}
};
func countSubarrays(nums []int, k int) int {
i, n := 0, len(nums)
for nums[i] != k {
i++
}
ans := 1
cnt := make([]int, n<<1|1)
x := 0
for j := i + 1; j < n; j++ {
if nums[j] > k {
x++
} else {
x--
}
if x >= 0 && x <= 1 {
ans++
}
cnt[x+n]++
}
x = 0
for j := i - 1; j >= 0; j-- {
if nums[j] > k {
x++
} else {
x--
}
if x >= 0 && x <= 1 {
ans++
}
ans += cnt[-x+n] + cnt[-x+1+n]
}
return ans
}
function countSubarrays(nums: number[], k: number): number {
const i = nums.indexOf(k);
const n = nums.length;
const cnt = new Array((n << 1) | 1).fill(0);
let ans = 1;
let x = 0;
for (let j = i + 1; j < n; ++j) {
x += nums[j] > k ? 1 : -1;
ans += x >= 0 && x <= 1 ? 1 : 0;
++cnt[x + n];
}
x = 0;
for (let j = i - 1; ~j; --j) {
x += nums[j] > k ? 1 : -1;
ans += x >= 0 && x <= 1 ? 1 : 0;
ans += cnt[-x + n] + cnt[-x + 1 + n];
}
return ans;
}