【LeetCode 面试经典150题】169. Majority Element 多数元素

169. Majority Element

题目大意

Given an array nums of size n, return the majority element.

The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.

中文释义

给定一个大小为 n 的数组 nums,返回多数元素。

多数元素是指在数组中出现次数超过 ⌊n / 2⌋ 的元素。你可以假设数组中总是存在多数元素。

示例

Example 1:

  • Input: nums = [3,2,3]
  • Output: 3

Example 2:

  • Input: nums = [2,2,1,1,1,2,2]
  • Output: 2

Constraints:

  • n == nums.length
  • 1 <= n <= 5 * 10^4
  • -10^9 <= nums[i] <= 10^9

解题思路

算法描述 - 摩尔投票法

使用了摩尔投票法来找到数组中的多数元素。多数元素定义为在数组中出现次数超过数组长度一半的元素。

  1. 初始化变量:

    • candidate: 作为多数元素的候选,初始设为数组的第一个元素。
    • cnt: 记录候选元素的"积分",初始设为1,代表候选元素的初始积分。
  2. 遍历数组 - 应用摩尔投票法:

    • 从数组的第二个元素开始遍历。
    • 摩尔投票法的核心在于配对不同的元素并消除它们。具体实现为:
      • 如果 cnt 为0,说明之前的候选元素和其他元素已经完全抵消,因此需要选取当前元素作为新的候选元素,并重置 cnt 为1。
      • 在遍历过程中,如果当前元素与候选元素相同,cnt 加1(增加积分);如果不同,则 cnt 减1(减少积分)。
  3. 返回结果:

    • 遍历完成后,由于多数元素的数量超过数组长度的一半,所以最终剩下的 candidate 即为所求的多数元素。
cpp 复制代码
class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int candidate = nums[0], cnt = 1;
        for (int i = 1; i < nums.size(); i++) {
            if (cnt == 0) {
                candidate = nums[i];
                cnt = 1;
            } else {
                cnt = candidate == nums[i] ? cnt + 1 : cnt - 1;
            }
        }
        return candidate;
    }
};
相关推荐
珹洺5 分钟前
C++算法竞赛篇:DevC++ 如何进行debug调试
java·c++·算法
Norvyn_715 分钟前
LeetCode|Day18|20. 有效的括号|Python刷题笔记
笔记·python·leetcode
前端小巷子38 分钟前
Web 实时通信:从短轮询到 WebSocket
前端·javascript·面试
呆呆的小鳄鱼43 分钟前
leetcode:冗余连接 II[并查集检查环][节点入度]
算法·leetcode·职场和发展
墨染点香44 分钟前
LeetCode Hot100【6. Z 字形变换】
java·算法·leetcode
沧澜sincerely44 分钟前
排序【各种题型+对应LeetCode习题练习】
算法·leetcode·排序算法
CQ_07121 小时前
自学力扣:最长连续序列
数据结构·算法·leetcode
弥彦_1 小时前
cf1925B&C
数据结构·算法
YuTaoShao1 小时前
【LeetCode 热题 100】994. 腐烂的橘子——BFS
java·linux·算法·leetcode·宽度优先
Wendy14419 小时前
【线性回归(最小二乘法MSE)】——机器学习
算法·机器学习·线性回归