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;
}
相关推荐
不会就选b7 小时前
算法日常・每日刷题--<贪心>7
数据结构·算法·leetcode
smj2302_7968265214 小时前
解决leetcode第4017题数组中的峰值II
python·算法·leetcode
午彦琳14 小时前
2026.9.9
数据结构·算法·leetcode
橘子汽水16815 小时前
Leetcode 200,994岛屿数量,腐烂的橘子
数据结构·算法·leetcode
Tisfy17 小时前
LeetCode 3871.统计范围内的逗号 II:每次算一个逗号
数学·算法·leetcode·题解
find1star18 小时前
LeetCode 54:螺旋矩阵——用四个边界模拟矩阵收缩
java·算法·leetcode·边缘计算·学习方法
吞下星星的少年·-·18 小时前
LeetCode 热题 100 两数之和(哈希表)
算法·leetcode·哈希算法
土司大王19 小时前
LeetCode hot100——全排列
java·算法·leetcode
203号居民19 小时前
LeetCode hot 100 — 138. 随机链表的复制
算法·leetcode·链表
土司大王20 小时前
LeetCode hot100——实现 Trie (前缀树)
java·算法·leetcode