1
0
mirror of https://gitee.com/coder-xiaomo/leetcode-problemset synced 2025-01-10 18:48:13 +08:00
Code Issues Projects Releases Wiki Activity GitHub Gitee
leetcode-problemset/leetcode-cn/problem (Chinese)/子数组中占绝大多数的元素 [online-majority-element-in-subarray].html
2022-03-29 12:43:11 +08:00

42 lines
1.6 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<p>设计一个数据结构,有效地找到给定子数组的 <strong>多数元素</strong></p>
<p>子数组的 <strong>多数元素</strong> 是在子数组中出现&nbsp;<code>threshold</code>&nbsp;次数或次数以上的元素。</p>
<p>实现 <code>MajorityChecker</code> 类:</p>
<ul>
<li><code>MajorityChecker(int[] arr)</code>&nbsp;会用给定的数组 <code>arr</code>&nbsp;&nbsp;<code>MajorityChecker</code> 初始化。</li>
<li><code>int query(int left, int right, int threshold)</code>&nbsp;返回子数组中的元素 &nbsp;<code>arr[left...right]</code>&nbsp;至少出现&nbsp;<code>threshold</code>&nbsp;次数,如果不存在这样的元素则返回 <code>-1</code></li>
</ul>
<p>&nbsp;</p>
<p><strong>示例 1</strong></p>
<pre>
<strong>输入:</strong>
["MajorityChecker", "query", "query", "query"]
[[[1, 1, 2, 2, 1, 1]], [0, 5, 4], [0, 3, 3], [2, 3, 2]]
<strong>输出:</strong>
[null, 1, -1, 2]
<b>解释:</b>
MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]);
majorityChecker.query(0,5,4); // 返回 1
majorityChecker.query(0,3,3); // 返回 -1
majorityChecker.query(2,3,2); // 返回 2
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 &lt;= arr.length &lt;= 2 * 10<sup>4</sup></code></li>
<li><code>1 &lt;= arr[i] &lt;= 2 * 10<sup>4</sup></code></li>
<li><code>0 &lt;= left &lt;= right &lt; arr.length</code></li>
<li><code>threshold &lt;= right - left + 1</code></li>
<li><code>2 * threshold &gt; right - left + 1</code></li>
<li>调用&nbsp;<code>query</code>&nbsp;的次数最多为&nbsp;<code>10<sup>4</sup></code>&nbsp;</li>
</ul>