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;
}
相关推荐
旖旎夜光8 小时前
LeetCode 202:快乐数(双指针问题) —— 题解
数据结构·c++·算法·leetcode·双指针
君君思密达9 小时前
Leetcode Hot 100 题目详解-哈希表
数据结构·算法·leetcode
203号居民10 小时前
LeetCode hot 100 —560. 和为 K 的子数组
java·算法·leetcode
退休倒计时10 小时前
【每日一题】LeetCode 20. 有效的括号 TypeScript
算法·leetcode·职场和发展·typescript
Forever Nore11 小时前
LeetCode 5 最长回文子串 - 中心扩散
linux·算法·leetcode
Forever Nore12 小时前
LeetCode 6 Z 字形变换 - 按行模拟
算法·leetcode
wabs66614 小时前
关于哈希表【力扣383.赎金信的思考】
算法·leetcode·散列表
.道阻且长.1 天前
2.LeetCode算法习题讲解--双指针--复写零
算法·leetcode·职场和发展
To_OC1 天前
LC 438 找到所有字母异位词:暴力超时后,我靠滑动窗口一招搞定
javascript·算法·leetcode
Tisfy1 天前
LeetCode 3731.找出缺失的元素:哈希 / 排序
算法·leetcode·哈希算法·排序·哈希表