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;
}
相关推荐
Shaoshing3 小时前
LeetCode100 76.最小覆盖字串
java·算法·leetcode
Navigator_Z6 小时前
LeetCode //C - 1331. Rank Transform of an Array
c语言·算法·leetcode
Tisfy6 小时前
LeetCode 1202.交换字符串中的元素:分组排序(连通图)
算法·leetcode·字符串·bfs·题解·排序·连通图
小白的高手之路1 天前
【LeetCode 热题 100】206. 反转链表|链表、迭代、递归(Python)
笔记·python·算法·leetcode·链表·职场和发展·力扣
16月6日-晴1 天前
122. 买卖股票的最佳时机 II【贪心】
算法·leetcode
小白的高手之路1 天前
【【LeetCode 热题 100】160. 相交链表|链表、哈希表、双指针(Python)
python·算法·leetcode·链表·力扣·散列表
灯澜忆梦1 天前
拓扑排序(Kahn BFS)| LeetCode 210 课程表 II
算法·leetcode·排序算法·宽度优先
Nuanyt1 天前
LeetCode Hot 100 贪心算法专题 121 / 55 / 45 / 763 (Java)
java·算法·leetcode·贪心算法·dp
吞下星星的少年·-·2 天前
LeetCode 热题 100 最长连续序列(哈希表)
算法·leetcode·散列表
Pniubi2 天前
力扣25.K个一组反转链表
算法·leetcode·链表