【发布时间】:2014-04-23 10:37:49
【问题描述】:
给定一个具有 n 行和 k 列的二维数组(矩阵),其中行已排序,列未指定,对它进行排序的最有效算法是什么?
例如:
Input (n = 3 ; k = 4):
1 5 8 10
3 4 5 6
2 3 3 9
Output:
1 2 3 3 3 4 5 5 6 8 9 10
这纯粹是算法问题,因此某些语言的特定 .sort() 方法没有帮助我,因为我实际上对运行时复杂性感兴趣。
我想到的算法如下:
- Build a Binary Search tree with n nodes. Each node contains:
ID - of the row it refers to;
Value - The number at the "head" of the row.
- Sort the tree where the sorting key are the values.
- Find the lowest valued node.
- Do while the tree has a root:
- Take the lowest value and append it to the new array.
- Update the node's value to the next one in the same row.
- If the updated value is null, delete that node.
- else re-sort the tree.
- If the node moved, the first node it swapped with will be the next lowest
- else, if it didn't move, it's the new lowest.
如果我没记错的话,运行时复杂度是O(n*k * log n),因为我正在对树进行n*k 次排序,这需要O(log n) 时间,并且找到下一个最低值的过程是O(1)。
如果我的复杂度计算有误,请告诉我。
还有比这更有效的方法吗?
【问题讨论】: