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;
}
相关推荐
期末考复习中,蓝桥杯都没时间学了19 分钟前
力扣刷题13
数据结构·算法·leetcode
会飞的战斗鸡34 分钟前
JS中的链表(含leetcode例题)
javascript·leetcode·链表
多米Domi01140 分钟前
0x3f 第48天 面向实习的八股背诵第五天 + 堆一题 背了JUC的题,java.util.Concurrency
开发语言·数据结构·python·算法·leetcode·面试
渐暖°1 小时前
【leetcode算法从入门到精通】5. 最长回文子串
vscode·算法·leetcode
今天_也很困1 小时前
LeetCode热题100-560. 和为 K 的子数组
java·算法·leetcode
v_for_van1 小时前
力扣刷题记录2(无算法背景,纯C语言)
c语言·算法·leetcode
alphaTao1 小时前
LeetCode 每日一题 2026/1/26-2026/2/1
算法·leetcode
We་ct2 小时前
LeetCode 54. 螺旋矩阵:两种解法吃透顺时针遍历逻辑
前端·算法·leetcode·矩阵·typescript
We་ct3 小时前
LeetCode 36. 有效的数独:Set实现哈希表最优解
前端·算法·leetcode·typescript·散列表
tod1134 小时前
力扣高频 SQL 50 题阶段总结(四)
开发语言·数据库·sql·算法·leetcode