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;
}
相关推荐
chengooooooo6 小时前
leetcode Top100 238. 除自身以外数组的乘积|数组系列
算法·leetcode
GalaxyPokemon9 小时前
LeetCode - 53. 最大子数组和
算法·leetcode·职场和发展
hn小菜鸡10 小时前
LeetCode 1356.根据数字二进制下1的数目排序
数据结构·算法·leetcode
zhuiQiuMX10 小时前
分享今天做的力扣SQL题
sql·算法·leetcode
全栈凯哥12 小时前
Java详解LeetCode 热题 100(26):LeetCode 142. 环形链表 II(Linked List Cycle II)详解
java·算法·leetcode·链表
全栈凯哥13 小时前
Java详解LeetCode 热题 100(27):LeetCode 21. 合并两个有序链表(Merge Two Sorted Lists)详解
java·算法·leetcode·链表
SuperCandyXu13 小时前
leetcode2368. 受限条件下可到达节点的数目-medium
数据结构·c++·算法·leetcode
蒟蒻小袁14 小时前
力扣面试150题--被围绕的区域
leetcode·面试·深度优先
GalaxyPokemon15 小时前
LeetCode - 148. 排序链表
linux·算法·leetcode
chao_78917 小时前
链表题解——环形链表 II【LeetCode】
数据结构·leetcode·链表