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;
}
相关推荐
We་ct20 分钟前
LeetCode 191. 位1的个数:两种解法详解
前端·算法·leetcode·typescript
北顾笙98040 分钟前
day13-数据结构力扣
数据结构·算法·leetcode
生信研究猿40 分钟前
leetcode 1.两数之和(重刷)
算法·leetcode·职场和发展
查古穆1 小时前
堆-前 K 个高频元素
数据结构·算法·leetcode
abant21 小时前
leetcode 105 前序中序构建二叉树
算法·leetcode·职场和发展
6Hzlia1 小时前
【Hot 100 刷题计划】 LeetCode 438. 找到字符串中所有字母异位词 | C++ 滑动窗口题解
c++·算法·leetcode
生信研究猿1 小时前
leetcode 234.回文链表
python·leetcode·链表
倦王1 小时前
力扣日刷复习:
算法·leetcode·职场和发展
py有趣1 小时前
力扣热门100题之二叉树的中序遍历
算法·leetcode·职场和发展
小辉同志2 小时前
17. 电话号码的字母组合
c++·算法·leetcode·深度优先