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;
}
相关推荐
Wenhao.1 小时前
LeetCode 救生艇
算法·leetcode·golang
夏鹏今天学习了吗1 小时前
【LeetCode热题100(69/100)】字符串解码
linux·算法·leetcode
小白程序员成长日记2 小时前
2025.11.18 力扣每日一题
算法·leetcode·职场和发展
未若君雅裁4 小时前
LeetCode 18 - 四数之和 详解笔记
java·数据结构·笔记·算法·leetcode
鱼骨不是鱼翅4 小时前
力扣hot100----1day
python·算法·leetcode·职场和发展
小欣加油5 小时前
leetcode 429 N叉树的层序遍历
数据结构·c++·算法·leetcode·职场和发展
Kuo-Teng5 小时前
LeetCode 142: Linked List Cycle II
java·算法·leetcode·链表·职场和发展
ada7_5 小时前
LeetCode(python)——73.矩阵置零
python·算法·leetcode·矩阵
1白天的黑夜17 小时前
递归-二叉树中的剪枝-814.二叉树剪枝-力扣(LeetCode)
c++·leetcode·剪枝·递归
前进之路98 小时前
Leetcode每日一练--47
数据结构·算法·leetcode