LeetCode 3134 找出唯一性数组的中位数
方法1:二分 + 滑动窗口 + 哈希表
class Solution {
public int medianOfUniquenessArray(int[] nums) {
int n = nums.length;
// 左中位数下标 下标从 1 开始
long median = ((long) n * (n + 1) / 2 + 1) / 2;
int left = 1, right = n;
while (left < right) {
int mid = (left + right) >> 1;
if (check(nums, median, mid))
right = mid;
else
left = mid + 1;
}
return left;
}
public boolean check(int[] nums, long median, int mid) {
// HashMap 统计不同元素个数 保证其不超过 mid
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int left = 0; long cnt = 0; // 统计满足添加的区间个数
for (int right = 0; right < nums.length; right++) {
map.merge(nums[right], 1, Integer::sum);
while (map.size() > mid) {
if (map.merge(nums[left], -1, Integer::sum) == 0)
map.remove(nums[left]);
left++; // 滑动左区间
}
// 前面区间已统计 此处只统计以 nums[right] 结尾的子数组
cnt += right - left + 1;
}
return cnt >= median;
}
}
class Solution:
def medianOfUniquenessArray(self, nums: List[int]) -> int:
def check(num: int) -> bool:
dic = Counter(); left = 0; cnt = 0
for right, x in enumerate(nums):
dic[x] += 1
while len(dic) > num:
dic[nums[left]] -= 1
if dic[nums[left]] == 0:
del dic[nums[left]]
left += 1
cnt += right - left + 1
if cnt >= medium: # 提前剪枝
return True
return False
n = len(nums)
medium = (n * (n + 1) // 2 + 1) // 2
low = 1; high = n
while low < high:
mid = (low + high) >> 1
if check(mid):
high = mid
else:
low = mid + 1
return low
标签:cnt,27,nums,int,08,mid,2024,right,left
From: https://www.cnblogs.com/XuGui/p/18382497