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;
}
相关推荐
y1su3 小时前
Leetcode 字符串模板
java·数据结构·算法·leetcode·职场和发展·动态规划
Xin77010 小时前
LeetCode 46. 全排列(回溯法)
leetcode
文丑颜不良啊12 小时前
LeetCode476~500题目解析
java·leetcode
Tsuki_tl13 小时前
【优选算法:双指针】——复写零题解
java·c++·算法·leetcode·数组·双指针·复写零
Cccp.12315 小时前
【leetcode】(十四)从暴力递归到动态规划
数据结构·算法·leetcode·动态规划
旖旎夜光15 小时前
LeetCode 215: 数组中的第K个最大元素 (快速排序) —— 题解
c++·学习·算法·leetcode·力控
德彪稳坐倒骑驴16 小时前
Leetcode力扣刷题记录与题解
算法·leetcode·职场和发展
java_nnnn1 天前
LeetCode刷题滑动窗口(水果成篮+找到字符串中所有字母的异位词)Java
java·开发语言·leetcode
文丑颜不良啊1 天前
LeetCode276~300题目解析
java·leetcode
傅科摆 _ py1 天前
链表力扣复习
数据结构·leetcode·链表