[剑指offer:30]最小的k个数

/* 30:> 最小的k个数 1) 用数组的第k个数,进行基于快排的partion : O(n),但要修改数组 2)最小堆,(multiset)O(nlogk),无需修改数组,适合数据量大,而k小的时候 p169 */
int Partion(int ar[], int start, int end)//end->len
{
    int left = start;
    int right = end - 1;
    int Key = ar[left];
    while (left < right)
    {
        while (left<right && ar[right]>Key)
            right--;
        if (left < right)
        {
            ar[left] = ar[right];
            left++;
        }
        while (left < right && ar[left] < Key)
            left++;
        if (left < right)
        {
            ar[right] = ar[left];
            right--;
        }
    }
    ar[left] = Key;

    return left;
}

void GetLeastNum(int ar[], int n, int output[], int k)
{
    if (ar == NULL || output == NULL || n <= 0 || k <= 0)
        return;

    int start = 0;
    int end = n;
    int index = Partion(ar, start, end);

    while (index != k-1)
    {
        if (index > k - 1)
        {
            end = k;
            index = Partion(ar, start, end);
        }
        else
        {
            start = k + 1;
            index = Partion(ar, start,end);
        }
    }
    for (int i = 0; i < k; ++i)
        output[i] = ar[i];
}

//void test()
//{
// int input[8] = {4,5,1,6,2,7,3,8};
// int output[4] = { 0 };
//
// GetLeastNum(input, 8, output, 4);
// for (int i = 0; i < 4; ++i)
// cout << output[i] << endl;
//}

你可能感兴趣的:([剑指offer:30]最小的k个数)