✌粤嵌—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; 
}
相关推荐
土司大王8 小时前
LeetCode hot100 回溯专题总结:Java 通用模板、决策树模型
java·算法·leetcode·决策树
a1879272183110 小时前
【算法】链表(二):链表上的双指针——变速、异链与定距,和一份路程账本
数据结构·算法·leetcode·链表·go·指针·环形链表
hanlin0315 小时前
刷题笔记:力扣第287题-寻找重复数
笔记·算法·leetcode
橘子汽水16815 小时前
Leetcode 322 279 零钱兑换,完全平方数
算法·leetcode
土司大王16 小时前
LeetCode hot100——51.N 皇后:Java 回溯模板、列与对角线剪枝、O(n!) 复杂度分析
java·leetcode·剪枝
木井巳17 小时前
【记忆化搜索】斐波那契数
java·算法·leetcode·深度优先·剪枝·推荐算法
Navigator_Z1 天前
LeetCode //C - 1240. Tiling a Rectangle with the Fewest Squares
c语言·算法·leetcode
稻米哟1 天前
力扣100——双指针
算法·leetcode
橘子汽水1681 天前
Leetcode 198,118打家劫舍,杨辉三角
算法·leetcode