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;
}
相关推荐
好记性+烂笔头2 小时前
hot100_108. 将有序数组转换为二叉搜索树
算法·leetcode·职场和发展
tt5555555555552 小时前
每日一题——主持人调度(二)
c语言·数据结构·算法·leetcode·八股文
Dream it possible!15 小时前
LeetCode 热题 100_在排序数组中查找元素的第一个和最后一个位置(65_34_中等_C++)(二分查找)(一次二分查找+挨个搜索;两次二分查找)
c++·算法·leetcode
夏末秋也凉15 小时前
力扣-回溯-46 全排列
数据结构·算法·leetcode
南宫生15 小时前
力扣每日一题【算法学习day.132】
java·学习·算法·leetcode
柠石榴15 小时前
【练习】【回溯No.1】力扣 77. 组合
c++·算法·leetcode·回溯
Leuanghing15 小时前
【Leetcode】11. 盛最多水的容器
python·算法·leetcode
qy发大财15 小时前
加油站(力扣134)
算法·leetcode·职场和发展
qy发大财15 小时前
柠檬水找零(力扣860)
算法·leetcode·职场和发展
不想编程小谭20 小时前
力扣LeetCode: 2506 统计相似字符串对的数目
c++·算法·leetcode