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;
}
相关推荐
Nil2089 小时前
leetcode 98验证二叉搜索树
算法·leetcode·职场和发展
时针滴滴答啊13 小时前
最大子数组和
算法·leetcode·职场和发展
重生之后端学习14 小时前
15. 三数之和[中等]✅
java·数据结构·算法·leetcode·职场和发展
Nil20816 小时前
leetcode 108有序数组转换为二叉搜索树
数据结构·算法·leetcode
hn小菜鸡16 小时前
LeetCode 763、划分字母区间
数据结构·算法·leetcode
Nil20816 小时前
leetcode 102二叉树的层序遍历
算法·leetcode·职场和发展
土司大王18 小时前
LeetCode hot100——相交链表
算法·leetcode·链表
土司大王18 小时前
LeetCode hot100——回文链表
算法·leetcode·链表
evans在进步19 小时前
LeetCode 1143:最长公共子序列——Java 二维动态规划详解
java·leetcode·动态规划
重生之后端学习1 天前
283. 移动零[简单]✅
开发语言·数据结构·算法·leetcode·职场和发展