2024/4/1—力扣—主要元素

代码实现:

思路:摩尔投票算法

cpp 复制代码
int majorityElement(int *nums, int numsSize) {
    int candidate = -1;
    int count = 0;
    for (int i = 0; i < numsSize; i++) {
        if (count == 0) {
            candidate = nums[i];
        }
        if (nums[i] == candidate) {
            count++;
        } else {
            count--;
        }
    }
    count = 0;
    int length = numsSize;
    for (int i = 0; i < numsSize; i++) {
        if (nums[i] == candidate) {
            count++;
        }
    }
    return count * 2 > length ? candidate : -1;
}
相关推荐
小羊在睡觉1 小时前
力扣84. 柱状图中最大的矩形
后端·算法·leetcode·golang·go
sheeta19982 小时前
LeetCode 每日一题笔记 日期:2026.05.29 题目:3300. 最小元素
笔记·leetcode
_日拱一卒2 小时前
LeetCode:994腐烂的橘子
java·数据结构·算法·leetcode·深度优先
小白兔奶糖ovo6 小时前
【Leetcode】231. 2的幂
linux·算法·leetcode
过期动态7 小时前
【LeetCode 热题 100】接雨水
java·数据结构·算法·leetcode·职场和发展
圣保罗的大教堂11 小时前
leetcode 3300. 替换为数位和以后的最小元素 简单
leetcode
sheeta199811 小时前
LeetCode 每日一题笔记 日期:2026.05.27 题目:3121. 统计特殊字母的数量 II
笔记·算法·leetcode
Tisfy11 小时前
LeetCode 3300.替换为数位和以后的最小元素:一次遍历
数学·算法·leetcode·模拟
金牌归来发现妻女流落街头14 小时前
【LeetCode 第207题】
算法·leetcode·拓扑·领接表
alphaTao15 小时前
LeetCode 每日一题 2026/5/25-2026/5/31
算法·leetcode