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;
}
相关推荐
人道领域17 小时前
【LeetCode刷题日记】47.全排列Ⅱ
java·开发语言·算法·leetcode
Navigator_Z17 小时前
LeetCode //C - 1095. Find in Mountain Array
c语言·算法·leetcode
暖阳华笺1 天前
【数据结构与算法】哈希专题
数据结构·c++·算法·leetcode·哈希算法
AKA__Zas1 天前
芝士算法(滑动窗口片 2.0)
java·算法·leetcode·学习方法
四代水门1 天前
LeetCode刷算法题(C++)
c++·算法·leetcode
退休倒计时1 天前
【每日一题】LeetCode 53. 最大子数组和 TypeScript
数据结构·算法·leetcode·typescript
洛水水1 天前
【力扣100题】86.柱状图中最大的矩形
算法·leetcode·职场和发展
洛水水2 天前
【力扣100题】81.寻找两个正序数组的中位数
数据结构·算法·leetcode
洛水水2 天前
【力扣100题】85.每日温度
算法·leetcode·职场和发展
Kurisu_红莉栖2 天前
力扣56合并区间
算法·leetcode