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;
}
相关推荐
tachibana27 分钟前
hot100 课程表(207)
java·数据结构·算法·leetcode
旖-旎42 分钟前
《LeetCode 646 最长数对链 || LeetCode 1143 最长公共子序列》
c++·算法·leetcode·动态规划
Frostnova丶1 小时前
(15)LeetCode 189. 轮转数组
数据结构·算法·leetcode
伊玛目的门徒12 小时前
试用leetcode之典中典 二数之和问题
java·算法·leetcode
旖-旎16 小时前
《LeetCode647 回文子串 || LeetCode 5 最长回文子串》
c++·算法·leetcode·动态规划·哈希算法
怪兽学LLM19 小时前
LeetCode 105. 从前序与中序遍历序列构造二叉树:分治递归思路详解
算法·leetcode·职场和发展
退休倒计时20 小时前
【每日一题】LeetCode 39. 组合总和 TypeScript
算法·leetcode·typescript
Scabbards_21 小时前
面试Leetcode - Array
leetcode·面试·职场和发展
兰令水1 天前
hot100【acm版】【2026.7.13打卡-java版本】
java·开发语言·数据结构·算法·leetcode·面试
Tisfy1 天前
LeetCode 1291.顺次数:打表/枚举
算法·leetcode·题解·枚举·遍历