LeetCode 题解工作台

查询超过阈值频率最高元素

给你一个长度为 n 的整数数组 nums 和一个查询数组 queries ,其中 queries[i] = [l i , r i , threshold i ] 。 返回一个整数数组 ans ,其中 ans[i] 等于子数组 nums[l i ...r i ] 中出现 至少 threshold i …

category

0

题型

code_blocks

0

代码语言

hub

0

相关题

当前训练重点

困难 · Threshold Majority Queries core interview pattern

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 Threshold Majority Queries core interview pattern 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个长度为 n 的整数数组 nums 和一个查询数组 queries,其中 queries[i] = [li, ri, thresholdi]

返回一个整数数组 ans,其中 ans[i] 等于子数组 nums[li...ri] 中出现 至少 thresholdi 次的元素,选择频率 最高 的元素(如果频率相同则选择 最小 的元素),如果不存在这样的元素则返回 -1。

 

示例 1:

输入: nums = [1,1,2,2,1,1], queries = [[0,5,4],[0,3,3],[2,3,2]]

输出: [1,-1,2]

解释:

查询 子数组 阈值 频率表 答案
[0, 5, 4] [1, 1, 2, 2, 1, 1] 4 1 → 4, 2 → 2 1
[0, 3, 3] [1, 1, 2, 2] 3 1 → 2, 2 → 2 -1
[2, 3, 2] [2, 2] 2 2 → 2 2

 

示例 2:

输入:nums = [3,2,3,2,3,2,3], queries = [[0,6,4],[1,5,2],[2,4,1],[3,3,1]]

输出:[3,2,3,2]

解释:

查询 子数组 阈值 频率表 答案
[0, 6, 4] [3, 2, 3, 2, 3, 2, 3] 4 3 → 4, 2 → 3 3
[1, 5, 2] [2, 3, 2, 3, 2] 2 2 → 3, 3 → 2 2
[2, 4, 1] [3, 2, 3] 1 3 → 2, 2 → 1 3
[3, 3, 1] [2] 1 2 → 1 2

 

提示:

  • 1 <= nums.length == n <= 104
  • 1 <= nums[i] <= 109
  • 1 <= queries.length <= 5 * 104
  • queries[i] = [li, ri, thresholdi]
  • 0 <= li <= ri < n
  • 1 <= thresholdi <= ri - li + 1
lightbulb

解题思路

方法一

1
2

speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Focus on how the candidate handles the query sorting and efficient sliding window techniques.

  • question_mark

    Look for an understanding of advanced query optimization methods like sqrt decomposition.

  • question_mark

    Check if the candidate can identify and address the potential pitfalls in query overlapping and frequency counting.

warning

常见陷阱

外企场景
  • error

    Failure to handle overlapping subarrays efficiently, leading to high time complexity.

  • error

    Incorrectly selecting the smallest element in case of a frequency tie.

  • error

    Not optimizing the solution with techniques like sqrt decomposition, resulting in poor performance on large inputs.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Consider handling dynamic updates to the array, where elements can be changed between queries.

  • arrow_right_alt

    Modify the problem to return the element with the highest frequency for all subarrays, not just those satisfying the threshold.

  • arrow_right_alt

    Extend the problem to multiple thresholds for each query, requiring additional logic for comparison.

help

常见问题

外企场景

查询超过阈值频率最高元素题解:Threshold Majority Quer… | LeetCode #3636 困难