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;
}
相关推荐
Swift社区14 小时前
LeetCode 421 - 数组中两个数的最大异或值
算法·leetcode·职场和发展
Kuo-Teng18 小时前
LeetCode 206: Reverse Linked List
java·算法·leetcode·职场和发展
做怪小疯子1 天前
LeetCode 热题 100——哈希——最长连续序列
算法·leetcode·哈希算法
Dream it possible!1 天前
LeetCode 面试经典 150_二叉树_二叉树展开为链表(74_114_C++_中等)
c++·leetcode·链表·面试·二叉树
做怪小疯子1 天前
LeetCode 热题 100——双指针——三数之和
算法·leetcode·职场和发展
sin_hielo1 天前
leetcode 2536
数据结构·算法·leetcode
flashlight_hi1 天前
LeetCode 分类刷题:203. 移除链表元素
算法·leetcode·链表
py有趣1 天前
LeetCode算法学习之数组中的第K个最大元素
学习·算法·leetcode
吗~喽1 天前
【LeetCode】将 x 减到 0 的最小操作数
算法·leetcode
flashlight_hi1 天前
LeetCode 分类刷题:3217. 从链表中移除在数组中存在的节点
javascript·数据结构·leetcode·链表