✌粤嵌—2024/3/20—多数元素

代码实现:

方法一:因为多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素,所以对元素排序后,n/2一定是多数元素------超时

cpp 复制代码
// 交换
void swap(int *m, int *n) {
    int temp = *m;
    *m = *n;
    *n = temp;
}

// 快速排序
// 左闭右开  l:左边第一个待排序元素下标  r:待排序元素个数
void quick_sort(int *arr, int l, int r) {
    if (r - l <= 2) {
        if (r - l <= 1) { // 没有或者只剩下一个
            return;
        }
        if (arr[l] > arr[r - 1]) { // 剩下两个
            swap(&arr[l], &arr[r - 1]);
        }
        return;
    }
    int i = l; // 左臂  下标
    int j = r - 1; // 右臂  下标
    int pivot = arr[i]; // 记录轴
    while (i < j) {
        while (i < j && arr[j] >= pivot) {
            j--;
        }
        if (i < j) {
            arr[i++] = arr[j];
        }
        while (i < j && arr[i] <= pivot) {
            i++;
        }
        if (i < j) {
            arr[j--] = arr[i];
        }
    }
    arr[i] = pivot;
    quick_sort(arr, l, i); // 左边递归
    quick_sort(arr, i + 1, r); // 右边递归
}

int majorityElement(int *nums, int numsSize) {
    quick_sort(nums, 0, numsSize);
    return nums[numsSize / 2];
}

方法二:摩尔投票法

cpp 复制代码
int majorityElement(int *nums, int numsSize) {
    int a = nums[0], flag = 1;
    for (int i = 1; i < numsSize; i++) {
        if (a == nums[i]) {
            flag++;
        } else {
            flag--;
            if (flag == 0) {
                a = nums[i];
                flag = 1;
            }
        }
    }
    return a; 
}
相关推荐
亮亮爱刷题9 天前
飞往大厂梦之算法提升-7
数据结构·算法·leetcode·动态规划
zmuy9 天前
124. 二叉树中的最大路径和
数据结构·算法·leetcode
chao_7899 天前
滑动窗口题解——找到字符串中所有字母异位词【LeetCode】
数据结构·算法·leetcode
Alfred king9 天前
面试150跳跃游戏
python·leetcode·游戏·贪心算法
呆呆的小鳄鱼9 天前
leetcode:746. 使用最小花费爬楼梯
算法·leetcode·职场和发展
YuTaoShao9 天前
【LeetCode 热题 100】42. 接雨水——(解法一)前后缀分解
java·算法·leetcode·职场和发展
YuforiaCode10 天前
(LeetCode 面试经典 150 题) 27.移除元素
算法·leetcode·面试
呆呆的小鳄鱼10 天前
leetcode:98. 验证二叉搜索树
算法·leetcode·职场和发展
alphaTao10 天前
LeetCode 每日一题 2025/6/16-2025/6/22
算法·leetcode
YuTaoShao10 天前
【LeetCode 热题 100】11. 盛最多水的容器——Java双指针解法
java·算法·leetcode