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;
}
相关推荐
优质酸酸乳2 小时前
力扣100题之21合并两个有序链表
算法·leetcode·链表
旖旎夜光2 小时前
LeetCode 137 : 只出现一次的数字 II(位运算) —— 题解
c++·笔记·学习·算法·leetcode·力控
yi0113 小时前
LeetCode 134 加油站:从 双循环暴力 演变到 贪心
linux·算法·leetcode
yi0114 小时前
DAY 14: LeetCode 394. 字符串解码|递归和栈到底怎么处理嵌套?
数据结构·笔记·python·算法·leetcode
P.D.Wei4 小时前
[Leetcode 1614] 括号的最大嵌套深度
算法·leetcode·职场和发展
blxr_5 小时前
力扣hot100寻找重复数https://leetcode.cn/problems/find-the-duplicate-number/
算法·leetcode·职场和发展
_不会dp不改名_6 小时前
leetcode_1614嵌套括号的最大深度
算法·leetcode·职场和发展
alphaTao8 小时前
LeetCode 每日一题 2026/9/21-2026/9/27
python·算法·leetcode
Persistent的粽子!20 小时前
双指针算法:最大盛水容器
c++·算法·leetcode
All for pursuit.1 天前
【二叉树-10】114.二叉树展开为链表
数据结构·c++·算法·leetcode·链表