2016-08-18 69 views
0

假设我们有一个二维数组最大的二维数组的列使用分而治之

1 2 3 1 
5 6 4 0 
0 3 2 1 
1 2 1 0 

有一个全球性的方式如何使用鸿沟找到列中的最大数目,如果攻克技术的长度每行都不一样?

我指的是寻找需要这一步骤的二维数组内峰的一个步骤。

一维数组它会是这样的

int maxNumber(vector<int> a , int min , int max){ 
    if(min == max) 
     return a[min]; 
    int mid = (min + max)/2; 
    int i = maxNumber(a , min , mid); 
    int j = maxNumber(a , mid +1, max); 
    if(i > j) 
     return i; 
    return j; 
    } 

    vector<int> v = { 1 , 2 , 5 , 0 , 10 , 9}; 
    cout << maxNumber(a , 0 , a.size() -1); 

现在对于N×N的N×M个或矩阵,我们可以做

int maxNumberCollum(vector<vector<int>> a , int row_min , int row_max , int size){ 
    if (row_min == row_max){ 
     return a[row_min][size]; 
    } 

    int row = (row_min + row_max)/2; 
    int i = maxNumberCollum(a , row_min , row  , size); 
    int j = maxNumberCollum(a , row + 1 , row_max , size); 

    if(i > j) 
     return i; 
    return j; 
}; 

vector< vector<int> > a = { { 1 , 2 , 3 }, 
          { 5 , 0 , 1 }, 
          { 6 , 2 , 0 } 
          }; 
cout << maxNumberCollum(a , 0 , a.size() -1 , 2) 

与列,我们希望作为参数传递给找到最大。

但是,如果我们不知道矩阵(2d数组)是NxN/NxM还是行的长度对于每一行都不相同,那么如何将它实现为2d数组将如何实现?

+2

对每个列执行1d的情况,然后对每个列的结果再次执行1d的情况? – David

+0

是D&C必须用来解决你的问题吗? – shole

+0

@shole这不是必须的,但我试图找出它使用D&C – Darlyn

回答

0

由于每个矢量都有其自己的大小,因此可以使用该信息来查找每行中的最大数。

如果你有这样一行:

return maxNumber(a[row_min], 0, a[row_min].size() - 1) 
+0

这实际上会导致不好的结果。另外,它不会让渐近复杂度变得更高,再次调用log n函数? – Darlyn

+1

您必须查看每个值才能在任何情况下找到最大值,所以您将始终具有NXM的复杂性。我看不出为什么它会抛出一个糟糕的结果,这是太模糊的描述 - 你应该使用调试器。此外,按照您的价值传递矢量,将会导致额外的副本。通过引用传递矢量可能是优选的。 –

+1

请注意,你可以做一个简单的嵌套循环,而不是分而治之。 –

0

如果考虑不同大小的矢量的矢量,关键的一点是:

return a[row_min][size]; 

通过调用你的1D函数替换确保你不会尝试访问那些超出范围的人。

举个例子,考虑下面的代码:

#include <iostream> 
#include <vector> 
#include <limits> 

using std::cout; 
using std::vector; 

const int lowest_int = std::numeric_limits<int>::lowest(); 

int max_number_in_column(const vector<vector<int>> &a, 
          size_t row_min, size_t row_max, size_t col) 
{ 
    if (row_min == row_max) { 
     return col < a[row_min].size() ? a[row_min][col] : lowest_int; 
    } 

    int row = (row_min + row_max)/2; 
    int i = maxNumberColumn(a, row_min, row,  col); 
    int j = maxNumberColumn(a, row + 1, row_max, col); 

    return i > j ? i : j; 
}; 

int main() { 
    vector<vector<int>> a = { 
     { 1 , 2 , 3 }, 
     { 5 , 0 , 1, -8 }, 
     { 6 , 2 } 
    }; 

    size_t col = 3; 
    int max = max_number_in_column(a, 0, a.size() - 1, col); 

    if (max > lowest_int) 
     cout << "The greater element of column " << col << " is " << max <<'\n'; 
    else 
     cout << "Unable to find a maximum value in column " << col << '\n'; 

    return 0; 
} 

我真的不明白的是为什么你正在尝试做这个使用分而治之的技术,而这将是一个更容易共同循环:

int max_number_in_column(const vector<vector<int>> &a , size_t col) 
{ 
    int max = lowest_int; 
    for (auto const &row : a) { 
     if (col < row.size() && row[col] > max) max = row[col]; 
    } 
    return max; 
};