✌粤嵌—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; 
}
相关推荐
ZHE|张恒4 小时前
LeetCode - 寻找两个正序数组的中位数
算法·leetcode
努力学算法的蒟蒻4 小时前
day03(11.1)——leetcode面试经典150
java·算法·leetcode
im_AMBER5 小时前
Leetcode 43
笔记·学习·算法·leetcode
mifengxing6 小时前
力扣每日一题——接雨水
c语言·数据结构·算法·leetcode·动态规划·
小南家的青蛙8 小时前
LeetCode LCR 085 括号生成
算法·leetcode·职场和发展
晨非辰8 小时前
《数据结构风云》递归算法:二叉树遍历的精髓实现
c语言·数据结构·c++·人工智能·算法·leetcode·面试
Dream it possible!8 小时前
LeetCode 面试经典 150_链表_LRU 缓存(66_146_C++_中等)(哈希表 + 双向链表)
c++·leetcode·链表·面试
小白菜又菜15 小时前
Leetcode 3370. Smallest Number With All Set Bits
算法·leetcode·职场和发展