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;
}
相关推荐
样例过了就是过了2 小时前
LeetCode热题100 N 皇后
数据结构·c++·算法·leetcode·dfs·深度优先遍历
样例过了就是过了4 小时前
LeetCode热题100 分割回文串
数据结构·c++·算法·leetcode·深度优先·dfs
Morwit5 小时前
【力扣hot100】 85. 最大矩形
c++·算法·leetcode·职场和发展
啊哦呃咦唔鱼6 小时前
LeetCode hot100-438 找到字符串中所以字母异位词
算法·leetcode·职场和发展
重生之后端学习6 小时前
136. 只出现一次的数字
开发语言·算法·leetcode·职场和发展·深度优先
luckycoding6 小时前
LCR 014.字符串的排列
leetcode
smj2302_796826526 小时前
解决leetcode第3869题.统计区间内奇妙数的数目
python·算法·leetcode
TracyCoder1237 小时前
LeetCode Hot100(66/100)——118. 杨辉三角
算法·leetcode·职场和发展
葳_人生_蕤7 小时前
Leetcode HOT 100
算法·leetcode·职场和发展
无尽的罚坐人生7 小时前
hot 100 35. 搜索插入位置
数据结构·算法·leetcode·二分查找