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;
}
相关推荐
海石12 小时前
1500分的题目,确实有实力,不过还是我略胜一筹
算法·leetcode
海石12 小时前
【记忆化搜索】条条大路通AC,走好适合你的那一条,走到后再考虑走得快
算法·leetcode
tachibana21 天前
hot100 排序链表(148)
java·数据结构·算法·leetcode·链表
不能跑的代码不是好代码1 天前
二叉树从基础概念到LeetCode实战
算法·leetcode
凯瑟琳.奥古斯特1 天前
二分查找解力扣1011最优运载能力
开发语言·c++·算法·leetcode·职场和发展
YuK.W2 天前
Leetcode100: 70.爬楼梯、118.杨辉三角、198.打家劫舍
java·算法·leetcode
旖-旎2 天前
《LeetCode 64 最小路径和 || LeetCode 174 地下城游戏》
c++·算法·leetcode·动态规划
凯瑟琳.奥古斯特2 天前
力扣1009补码解法C++实现
开发语言·c++·算法·leetcode·职场和发展
凯瑟琳.奥古斯特2 天前
力扣1008:前序重建BST
开发语言·c++·算法·leetcode·职场和发展
aqiu1111112 天前
【算法日记 13】LeetCode 49. 字母异位词分组:哈希表的进阶“降维打击”
算法·leetcode·散列表