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;
}
相关推荐
im_AMBER2 小时前
Leetcode 33
算法·leetcode·职场和发展
坚持编程的菜鸟4 小时前
LeetCode每日一题——二进制求和
c语言·算法·leetcode
爱coding的橙子8 小时前
每日算法刷题Day77:10.22:leetcode 二叉树bfs18道题,用时3h
算法·leetcode·职场和发展
Swift社区8 小时前
LeetCode 404:左叶子之和(Sum of Left Leaves)
算法·leetcode·职场和发展
一匹电信狗9 小时前
【C++】手搓AVL树
服务器·c++·算法·leetcode·小程序·stl·visual studio
野蛮人6号10 小时前
力扣热题100道之73矩阵置零
算法·leetcode·矩阵
野蛮人6号10 小时前
力扣热题100道之238除自身以外数组的乘积
算法·leetcode·职场和发展
坚持编程的菜鸟10 小时前
LeetCode每日一题——缀点成线
c语言·算法·leetcode
我搞slam21 小时前
快乐数--leetcode
算法·leetcode·哈希算法
西阳未落1 天前
LeetCode——二分(进阶)
算法·leetcode·职场和发展