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 78. 子集 TypeScript
算法·leetcode·typescript
旖-旎2 小时前
《LeetCode 978 最长湍流子数组 || LeetCode 139 单词拆分》
c++·算法·leetcode·动态规划
smj2302_7968265216 小时前
解决leetcode第3985题回文数组求和
数据结构·python·算法·leetcode
旖-旎20 小时前
《LeetCode 53 最大子数组和 || LeetCode 918 环形子数组的最大和》
c++·算法·leetcode·动态规划
海石1 天前
单调栈复健,顺便,牺牲一下吧,空间复杂度!一切献给AC
算法·leetcode
海石1 天前
JS击败94%,Hard题想不到动态规划,那就用数组和栈试试
算法·leetcode
alphaTao1 天前
LeetCode 每日一题 2026/7/6-2026/7/12
算法·leetcode
想吃火锅10051 天前
【leetcode】56.合并区间js
算法·leetcode·职场和发展
wabs6661 天前
关于动态规划【力扣72.编辑距离的思考】
算法·leetcode·动态规划
凌波粒1 天前
LeetCode--47.全排列 II(回溯算法)
算法·leetcode·职场和发展