mirror of
https://gitee.com/coder-xiaomo/leetcode-problemset
synced 2025-01-10 18:48:13 +08:00
40 lines
1.6 KiB
HTML
40 lines
1.6 KiB
HTML
<p>Design a data structure that efficiently finds the <strong>majority element</strong> of a given subarray.</p>
|
|
|
|
<p>The <strong>majority element</strong> of a subarray is an element that occurs <code>threshold</code> times or more in the subarray.</p>
|
|
|
|
<p>Implementing the <code>MajorityChecker</code> class:</p>
|
|
|
|
<ul>
|
|
<li><code>MajorityChecker(int[] arr)</code> Initializes the instance of the class with the given array <code>arr</code>.</li>
|
|
<li><code>int query(int left, int right, int threshold)</code> returns the element in the subarray <code>arr[left...right]</code> that occurs at least <code>threshold</code> times, or <code>-1</code> if no such element exists.</li>
|
|
</ul>
|
|
|
|
<p> </p>
|
|
<p><strong class="example">Example 1:</strong></p>
|
|
|
|
<pre>
|
|
<strong>Input</strong>
|
|
["MajorityChecker", "query", "query", "query"]
|
|
[[[1, 1, 2, 2, 1, 1]], [0, 5, 4], [0, 3, 3], [2, 3, 2]]
|
|
<strong>Output</strong>
|
|
[null, 1, -1, 2]
|
|
|
|
<strong>Explanation</strong>
|
|
MajorityChecker majorityChecker = new MajorityChecker([1, 1, 2, 2, 1, 1]);
|
|
majorityChecker.query(0, 5, 4); // return 1
|
|
majorityChecker.query(0, 3, 3); // return -1
|
|
majorityChecker.query(2, 3, 2); // return 2
|
|
</pre>
|
|
|
|
<p> </p>
|
|
<p><strong>Constraints:</strong></p>
|
|
|
|
<ul>
|
|
<li><code>1 <= arr.length <= 2 * 10<sup>4</sup></code></li>
|
|
<li><code>1 <= arr[i] <= 2 * 10<sup>4</sup></code></li>
|
|
<li><code>0 <= left <= right < arr.length</code></li>
|
|
<li><code>threshold <= right - left + 1</code></li>
|
|
<li><code>2 * threshold > right - left + 1</code></li>
|
|
<li>At most <code>10<sup>4</sup></code> calls will be made to <code>query</code>.</li>
|
|
</ul>
|