1
0
mirror of https://gitee.com/coder-xiaomo/leetcode-problemset synced 2025-11-12 15:25:48 +08:00
Code Issues Projects Releases Wiki Activity GitHub Gitee
Files
leetcode-problemset/leetcode-cn/problem (English)/统计主要元素子数组数目 II(English) [count-subarrays-with-majority-element-ii].html
2025-11-11 22:54:49 +08:00

62 lines
2.2 KiB
HTML
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<p>You are given an integer array <code>nums</code> and an integer <code>target</code>.</p>
<p>Return the number of <strong><span data-keyword="subarray-nonempty">subarrays</span></strong> of <code>nums</code> in which <code>target</code> is the <strong>majority element</strong>.</p>
<p>The <strong>majority element</strong> of a subarray is the element that appears <strong>strictly more than half</strong> of the times in that subarray.</p>
<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,2,3], target = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>Valid subarrays with <code>target = 2</code> as the majority element:</p>
<ul>
<li><code>nums[1..1] = [2]</code></li>
<li><code>nums[2..2] = [2]</code></li>
<li><code>nums[1..2] = [2,2]</code></li>
<li><code>nums[0..2] = [1,2,2]</code></li>
<li><code>nums[1..3] = [2,2,3]</code></li>
</ul>
<p>So there are 5 such subarrays.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1], target = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation: </strong></p>
<p><strong></strong>All 10 subarrays have 1 as the majority element.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], target = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><code>target = 4</code> does not appear in <code>nums</code> at all. Therefore, there cannot be any subarray where 4 is the majority element. Hence the answer is 0.</p>
</div>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
<li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>
<li><code>1 &lt;= target &lt;= 10<sup>9</sup></code></li>
</ul>