算法-查找数组中的前M大的数

查找数组中的前M大的数

  • 思路
根据快速排序的Partition的思想,假定数组长度为n, 选定一个pivot,总能将数组分为 [0,k-1]和[k,n], 
其中[0,k-1]<pivot,[k+1,n] > pivot。如果 k = m, 那么算法结束。如果k > m, 对[k+1,n]继续进行切分,
每次切分k都会减少一部分, 直到k = m, 如果k < m, 对[0,k-1]继续切分出m-k个大的数, 每次切分k都会
增加一部分,直到k = m。 
  • 算法复杂度

    平均算法复杂度为:O(n) = n,最坏情况的复杂度为:O(n) = n。

cpp实现
int Partition(int arr[], int start, int end) {
    int pivot = arr[start];
    int highvac = end;
    int lowvac = start;
    int direct = true; //true for right,false for left. start from left 
    while(lowvac < highvac) {
        if(direct == true) {
            if(arr[highvac] <pivot) {
                arr[lowvac] = arr[highvac];
                lowvac++;
                direct = false;
            } else {
                highvac--;
            }
        } else {
            if(arr[lowvac] > pivot) {
                arr[highvac] = arr[lowvac];
                highvac--;
                direct = true;
            } else {
                lowvac++;
            }
        }
    }
    arr[highvac] = pivot;
    return highvac;
}

int*  findXMaxValue(int arr[], int xmax, int start, int end) {
    int p = 0;
    static int*  maxs = new int[xmax];
    int cmax = end - start +1;
    int len  = end;
    if (xmax >= len+1) {
        return arr;
    }
    while(cmax != xmax) {
       p = Partition(arr,start,end);
       cmax = len-p+1;
        if(cmax > xmax) {
            start = p+1;
        }  else if ( cmax < xmax)  {
            end = p-1;
            start = 0;
        }
    }
    for(int j = 0; j < xmax;  j++) {
        maxs[j] = arr[p+j];
    }
    return maxs;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值