✌粤嵌—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; 
}
相关推荐
longlongzihan12 小时前
LeetCode 5. 最长回文子串:从暴力匹配到中心扩展的思维演进
c++·算法·leetcode
苦瓜打怪兽12 小时前
leetcode 热题100(11. 盛最多水的容器)
python·算法·leetcode
All for pursuit.16 小时前
【回溯-6】79.单词搜索
数据结构·c++·算法·leetcode
Navigator_Z16 小时前
LeetCode //C - 1281. Subtract the Product and Sum of Digits of an Integer
c语言·算法·leetcode
旖旎夜光19 小时前
LeetCode 1576: 替换所有的问号(模拟) —— 题解
c++·学习·算法·leetcode·力控
longlongzihan19 小时前
回溯法详解:LeetCode 46. 全排列
算法·leetcode·回溯
圣保罗的大教堂20 小时前
leetcode 3532. 针对图的路径存在性查询 I 中等
leetcode
longlongzihan1 天前
从LeetCode 70. 爬楼梯看动态规划:如何精准推导状态转移方程?
c++·算法·leetcode·动态规划
Rnan-prince2 天前
LeetCode 股票买卖系列:一个动态规划状态机模板通吃四题
leetcode·动态规划
圣保罗的大教堂2 天前
leetcode 3756. 连接非零数字并乘以其数字和 II 中等
leetcode