leetcode搬运工

3134.找出唯一性数组的中位数

给你一个整数数组 nums 。数组 nums 的 唯一性数组 是一个按元素从小到大排序的数组,包含了 nums 的所有非空 子数组中不同元素的个数。
换句话说,这是由所有 0 <= i <= j < nums.length 的 distinct(nums[i…j]) 组成的递增数组。其中,distinct(nums[i…j]) 表示从下标 i 到下标 j 的子数组中不同元素的数量。
返回 nums 唯一性数组 的 中位数 。

注意:数组的 中位数 定义为有序数组的中间元素。如果有两个中间元素,则取值较小的那个。

示例 1

输入:nums = [1,2,3]

输出:1

解释:nums 的唯一性数组为 [distinct(nums[0..0]), distinct(nums[1..1]),distinct(nums[2..2]), distinct(nums[0..1]), distinct(nums[1..2]),distinct(nums[0..2])],即 [1, 1, 1, 2, 2, 3] 。唯一性数组的中位数为 1 ,因此答案是 1 。

示例 2

输入:nums = [3,4,3,4,5]

输出:2

解释:nums 的唯一性数组为 [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3] 。唯一性数组的中位数为 2 ,因此答案是 2 。

示例 3

输入:nums = [4,3,5,4]

输出:2

解释:nums 的唯一性数组为 [1, 1, 1, 1, 2, 2, 2, 3, 3, 3] 。唯一性数组的中位数为 2 ,因此答案是 2 。

答案:

class Solution:
    def medianOfUniquenessArray(self, nums: List[int]) -> int:
        n=len(nums)
        median = (n*(n+1)//2+1)//2
        def check(t):
            cnt=Counter() #哈希统计数组
            j,tot=0,0
            for i,v in enumerate(nums): #枚举
                cnt[v]+=1 #出现次数加1
                while len(cnt)>t: #哈希表 cnt 中元素的数目超过 t,就不断移出窗口左端点元素 nums[j]
                    cnt[nums[j]]-=1 #nums[j] 出现的次数减去 1
                    if cnt[nums[j]]==0:
                        del cnt[nums[j]] #从哈希表 cnt 中移除
                    j+=1
                tot+=i-j+1
         # 否满足 tot≥median,如果满足则缩小 t,直到找到最小的 t 返回即可
            return tot>=median

        res=0
        lo,hi=1,n
        # 二分查找
        while lo<=hi:
            mid=(lo+hi)//2
            if check(mid):
                res=mid
                hi=mid-1
            else:
                lo=mid+1
        return res
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值