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;
}
相关推荐
杰克尼1 小时前
1. 两数之和 (leetcode)
数据结构·算法·leetcode
YuTaoShao2 小时前
【LeetCode 热题 100】56. 合并区间——排序+遍历
java·算法·leetcode·职场和发展
JoJo_Way6 小时前
LeetCode三数之和-js题解
javascript·算法·leetcode
凌肖战9 小时前
力扣网C语言编程题:在数组中查找目标值位置之二分查找法
c语言·算法·leetcode
GEEK零零七11 小时前
Leetcode 1103. 分糖果 II
数学·算法·leetcode·等差数列
重庆小透明12 小时前
力扣刷题记录【1】146.LRU缓存
java·后端·学习·算法·leetcode·缓存
desssq12 小时前
力扣:70. 爬楼梯
算法·leetcode·职场和发展
岁忧14 小时前
(LeetCode 面试经典 150 题 ) 58. 最后一个单词的长度 (字符串)
java·c++·算法·leetcode·面试·go
??tobenewyorker16 小时前
力扣打卡第二十一天 中后遍历+中前遍历 构造二叉树
数据结构·c++·算法·leetcode
凌肖战19 小时前
力扣网C语言编程题:快慢指针来解决 “寻找重复数”
c语言·算法·leetcode