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;
}
相关推荐
52Hz1182 小时前
力扣20.有效的括号、155.最小栈
python·算法·leetcode
菜鸡儿齐2 小时前
leetcode-电话号码的字母组合
算法·leetcode·职场和发展
We་ct3 小时前
LeetCode 236. 二叉树的最近公共祖先:两种解法详解(递归+迭代)
前端·数据结构·算法·leetcode·typescript
小白菜又菜3 小时前
Leetcode 229. Majority Element II
算法·leetcode·职场和发展
Frostnova丶3 小时前
LeetCode 1461. 检查一个字符串是否包含所有长度为 K 的二进制子串
算法·leetcode·哈希算法
历程里程碑3 小时前
普通数组---合并区间
java·大数据·数据结构·算法·leetcode·elasticsearch·搜索引擎
小白菜又菜4 小时前
Leetcode 236. Lowest Common Ancestor of a Binary Tree
python·算法·leetcode
不想看见4044 小时前
01 Matrix 基本动态规划:二维--力扣101算法题解笔记
c++·算法·leetcode
Navigator_Z5 小时前
LeetCode //C - 964. Least Operators to Express Number
c语言·算法·leetcode
骇城迷影6 小时前
代码随想录:二叉树篇(中)
数据结构·c++·算法·leetcode