LeetCode215 | Kth largest element in the array

      Find the k-th largest element in the unsorted array. Please note that what you need to find is the k-th largest element after sorting the array, not the k-th different element.

Example 1:

Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:

Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
 

You can assume that k is always valid, and 1 ≤ k ≤ the length of the array.


      For specific ideas, see this article: Recursion and Divide and Conquer | 1: Select Algorithm/Median-Example: Oil Well . This article seeks the Kth smallest element, and this question seeks the Kth largest element. It only needs small changes, and the idea is the same.

      The AC code is attached below:

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);
}

 

Guess you like

Origin blog.csdn.net/weixin_43787043/article/details/106934361