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;
}
相关推荐
玖玥拾3 小时前
LeetCode 88 合并两个有序数组
算法·leetcode
Hi李耶4 小时前
【LeetCode】541.反转字符串 II
算法·leetcode·职场和发展
白白白小纯9 小时前
每日算法day3—回文链表,链表分割
c语言·数据结构·算法·leetcode
zander25810 小时前
35. 搜索插入位置:从边界语义理解二分查找
数据结构·算法·leetcode
yyds_yyd_1008611 小时前
3731. 找出缺失的元素(2026.08.04)
c++·leetcode
lueluelue4719 小时前
LeetCode:链表
算法·leetcode·链表
橘子汽水1681 天前
Leetcode 23,543合并K个升序链表,二叉树的直径
算法·leetcode·链表
Re.不晚1 天前
挑战做100道力扣算法- DAY1
算法·leetcode·职场和发展
青山木1 天前
Hot 100 --- 搜索插入位置
java·数据结构·算法·leetcode
星轨初途1 天前
LeetCode 热题 100——day2 字母异位词分组
c++·算法·leetcode