LeetCode215 | 数组中的第K个最大元素

      在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。

示例 1:

输入: [3,2,1,5,6,4] 和 k = 2
输出: 5
示例 2:

输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
输出: 4
 

你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。


      具体的思路看这一篇文章:递归与分治 | 1:选择算法/中位数 —— 例题:油井。此文是求第K个最小元素,而此题求第K个最大元素。只需要小小改动即可,思路一样。

      下面附上AC代码:

void swap(int a[], int i, int j) {
    int t = a[i];
    a[i] = a[j];
    a[j] = t;
}

/* 将数组a的[s, e]范围,按照与pivot的大小关系,划分到pivot两侧 *
 * 返回pivot最终的下标
 * 注:pivot是随机选取的 */
int RandomizedPartition(int a[], int s, int e) {
    int pivot = a[e]; //取最后一个元素为pivot来划分
    int i = s, j = e - 1;
    while (i < j) {
        while (a[i] >= pivot && i < e - 1)
            i++;
        while (a[j] <= pivot && j > s)
            j--;
        if (i < j)
            swap(a, i, j);
    }

    if(a[i] > pivot)   //所有元素都比pivot大,原序列不需要调整
        return e;
    else {
        swap(a, i, e);   //将pivot转到合适位置
        return i;
    }
}

/* 找数组a[s, e]范围内的第k小元素 */
int RandomizedSelect(int a[], int s, int e, int k) {
    int pivot_index = RandomizedPartition(a, s, e); //按照与pivot的大小关系,划分到pivot两侧。返回pivot最终的下标
    int num = pivot_index - s + 1; //pivot(包括在内)左侧的元素个数

    if (num == k)//第k小元素恰好是pivot
        return a[pivot_index];
    else if (k < num)   //在pivot左边找
        return RandomizedSelect(a, s, pivot_index - 1, k);
    else  //在pivot右边找
        return RandomizedSelect(a, pivot_index + 1, e, k - num);
}

int findKthLargest(int* nums, int numsSize, int k){
    return RandomizedSelect(nums, 0, numsSize - 1, k);
}

猜你喜欢

转载自blog.csdn.net/weixin_43787043/article/details/106934361