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;
}
相关推荐
剑挑星河月4 小时前
234. 回文链表
java·数据结构·算法·leetcode·链表
硕风和炜15 小时前
【LeetCode: 2492. 两个城市间路径的最小分数 + DFS】
java·算法·leetcode·深度优先·dfs·bfs·并查集
凯瑟琳.奥古斯特17 小时前
K次取反最大化数组和解法(力扣1005)
开发语言·c++·算法·leetcode·职场和发展
tachibana220 小时前
hot100 回文链表(234)
java·网络·数据结构·leetcode·链表
wabs6661 天前
关于动态规划【力扣1143.最长公共子序列的思考】
算法·leetcode·动态规划
剑挑星河月1 天前
54.螺旋矩阵
java·算法·leetcode·矩阵
笨笨没好名字1 天前
Leetcode刷题python3版第一周(下)
linux·算法·leetcode
青山木1 天前
Hot 100 --- LRU 缓存
java·数据结构·算法·leetcode·链表·缓存·哈希
想你依然心痛1 天前
AtomCode在算法竞赛中的实战体验:LeetCode周赛辅助编程
linux·算法·leetcode
剑挑星河月1 天前
35.搜索插入位置
java·数据结构·算法·leetcode