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;
}
相关推荐
想吃火锅10054 小时前
【leetcode】238.除了自身以外数组的乘积js
javascript·算法·leetcode
Tisfy5 小时前
LeetCode 0020.有效的括号:栈匹配
算法·leetcode·字符串·题解·括号匹配
Navigator_Z6 小时前
LeetCode //C - 1276. Number of Burgers with No Waste of Ingredients
c语言·算法·leetcode
想吃火锅10056 小时前
【leetcode】189.轮转数组js
开发语言·javascript·leetcode
All for pursuit.8 小时前
【贪心-2】253.会议室 II
数据结构·c++·算法·leetcode
All for pursuit.1 天前
【分治-3】347.前K个高频元素
数据结构·c++·算法·leetcode
All for pursuit.1 天前
【二分查找-2】34.在排序数组中查找元素的第一个和最后一个位置
数据结构·c++·算法·leetcode
blxr_1 天前
力扣hot100爬楼梯https://leetcode.cn/problems/climbing-stairs/
算法·leetcode·职场和发展
Navigator_Z1 天前
LeetCode //C - 1275. Find Winner on a Tic Tac Toe Game
c语言·算法·leetcode
All for pursuit.1 天前
【分治-2】215.数组中的第K个最大元素
数据结构·c++·算法·leetcode