按字典顺序对二维数组进行排序
给定一个具有N行可变大小的二维数组arr[] ,任务是按字典顺序对数组进行排序,即按字典顺序对每一行进行排序,然后对这些排序的行进行排序。
例子:
Input: arr[][] = { {23}, {59}, {23, 59} }
Output: { {23}, {23, 59}, {59} }
Explanation: The rows are sorted lexicographically.
Here the row {23, 59} is lexicographically smaller than {59}
because the first element (23) is smaller than 59.
Though {23} and {23, 59} both have 23 as the first element but {23} has only one element.
Hence {23} is lexicographically smaller than {23, 59}
Input: arr[][] = { {3, 2, 5, 6}, {1, 2, 3}, {6, 3}, {5, 4, 2} }
Output: { {1, 2, 3}, {2, 3, 5, 6}, {2, 4, 5}, {3, 6} }
Input: arr[][] = { {3, 2, 5, 6}, {, 2, 3, 5}, {2, 4, 2, 1}, {6, 3, 7, 8} }
Output: { {1, 2, 2, 4}, {1, 2, 3, 5}, {2, 3, 5, 6}, {3, 6, 7, 8} }
方法:解决问题的思路如下:
Smallest lexicographical order can be obtained by sorting the elements of each row and first then sorting the whole 2D array based on the lexicographical order of elements in each row.
请按照以下步骤解决此问题:
- 首先,按字典顺序对给定二维数组的每一行进行排序。
- 根据每行元素的字典顺序对整个二维数组进行排序。按字典顺序较小的行将首先到达排序矩阵。
- 打印二维数组。
下面是上述方法的实现:
C++
// C++ code to implement the approach
#include
using namespace std;
// Function to sort the 2D array
// lexicographically
void sort_lexicographically(vector >& arr)
{
for (int i = 0; i < arr.size(); ++i) {
// Initially sorting the array row-wise
sort(arr[i].begin(), arr[i].end());
}
// Sort the whole array in lexicographically
sort(arr.begin(), arr.end());
}
// Driver's code
int main()
{
vector > arr
= { { 3, 2, 5, 6 }, { 1, 2, 3 }, { 5, 4, 2 }, { 6, 3 }, { 9, 99 }, { 6, 3, 2 } };
sort_lexicographically(arr);
// Resultant 2-d array after
// sorting lexicographically
for (int i = 0; i < arr.size(); ++i) {
for (int j = 0; j < arr[i].size();
++j) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
1 2 3
2 3 5 6
2 3 6
2 4 5
3 6
9 99
时间复杂度: O(N*M*log(M)),其中N是行数, M是arr中一行的最大大小
辅助空间: O(1)