求最小的k個數

輸入n個整數,找出其中最小的k個數

    解法1:需要修改輸入的數組,基於partition快速排序來做,時間複雜福O(N)

    分析:基於數組的第k個元素來調整,使的比第k個數大的所有數字放到數組的右邊,這樣,數組左邊k個就是最小的k個數字

void GetLestNumber(int *input, int n, int *output, int k)
{
	if (input == NULL || output == NULL || k > n || n <= 0 || k <= 0)
		return;

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

解法二:

    分析:先創建一個大小爲k的數據容器來存儲最小的k個數字,接着每次從輸入的n個整數中讀入一個數,如果容器中少於k個數則直接放,若大於則表示容器以滿,此時找出容器中最大值,然後拿輸入的值和最大值比較,若待插入的數小於最大值,則直接替換。

    最大堆的結構每次可以在O(1)得到最大值,但需要o(logk)時間來完成刪除及插入

    紅黑樹同上,但是代碼簡於大堆

void GetLestNumber(int *input, int n, int *output, int k)
{
        if (input == NULL || output == NULL || k > n || n <= 0 || k <= 0)
          return;

 int start = 0;
      int end = n - 1;
    int index = Partition(input, n, start, end);
        while (index != k - 1)
      {
           if (index > k - 1)
               {
                   end = index - 1;
                    index = Partition(input, n, start, end);
            }
           else
                {
                   start = index + 1;
                  index = Partition(input, n, start, end);
            }
   }
   for (int i = 0; i < k; ++i)
      {
           output[i] = input[i];
       }
}
解法二:
    分析:先創建一個大小爲k的數據容器來存儲最小的k個數字,接着每次從輸入的n個整數中讀入一個數,如果容器中少於k個數則直接放,若大於則表示容器以滿,此時找出容器中最大值,然後拿輸入的值和最大值比較,若待插入的數小於最大值,則直接替換。
    最大堆的結構每次可以在O(1)得到最大值,但需要o(logk)時間來完成刪除及插入
const int N = 1000;
const int k = 10;
void AdjustDown(int *a, int size, int parent)
{
 int child = (parent - 1) / 2;
       while (child < size)
     {
           if (child+1<size&&a[child]>a[child + 1])
                      child++;
            if (a[child]>a[parent])
          {
                   swap(a[child], a[parent]);
                  parent = child;
                     child = (parent - 1) / 2;
           }
           else
                        break;
      }
}
void GetTopK(int*a)
{
  assert(k < N);
   int top[k];
 for (int i = 0; i < k; i++)
      {
           top[i] = a[i];
      }
   for (int i = (k - 2) / 2; i >= 0; i++)
   {
           AdjustDown(top, k, i);
      }
   for (int i = N-k-1; i < N; i++)
  {
           if (a[i]>top[0])
         {
                   top[0] = a[i];
                      AdjustDown(top, k, 0);
              }
   }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章