LeetCode215 | Kth elemento más grande en la matriz

      Encuentre el k-ésimo elemento más grande en la matriz sin clasificar. Tenga en cuenta que lo que necesita encontrar es el k-ésimo elemento más grande después de ordenar la matriz, no el k-ésimo elemento diferente.

Ejemplo 1:

Entrada: [3,2,1,5,6,4] yk = 2
Salida: 5
Ejemplo 2:

Entrada: [3,2,3,1,2,4,5,5,6] yk = 4
Salida: 4
 

Puede asumir que k es siempre válido y 1 ≤ k ≤ la longitud de la matriz.


      Para obtener ideas específicas, consulte este artículo: Recursión y Divide y vencerás | 1: Seleccionar algoritmo / mediana-Ejemplo: pozo de petróleo . Este artículo busca el elemento Kth más pequeño, y esta pregunta busca el elemento Kth más grande. Solo necesita pequeños cambios y la idea es la misma.

      El código de CA se adjunta a continuación:

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

 

Supongo que te gusta

Origin blog.csdn.net/weixin_43787043/article/details/106934361
Recomendado
Clasificación