2017-04-06 47 views
-1

我们有一个n×n矩阵,其中每行和每列按升序排列。按行和明智排序的矩阵搜索

给出一个数字x,如何判断这个x是否在矩阵中,好于O(n)的复杂度?

+0

好于O(n)的复杂性?我不认为这是可能的。 – Rishav

+0

你有什么尝试不起作用? – Gene

+0

@Gene我可以做O(n)只需通过行和列进行搜索。 – Aaron

回答

2

我认为只是使用二进制搜索。

二进制搜索的时间复杂度为O(log(n))。因此,在n×n矩阵的情况下,时间复杂度为O(log(n^2))= O(2log(n))。

它比O(n)好。

-----(编辑)/这是我的cpp代码。

#include<vector> 
#include<iostream> 
#include<cstdio> 

using namespace std; 

int n = 10; 
vector<vector<int> > arr; 
int search_cnt; 

int _1to2(int x) 
{ 
    int row, col; 

    row = (x - 1)/n + 1; 
    if(x % n == 0) 
     col = n; 
    else 
     col = x % n; 

    return arr[row][col]; 
} 

int _2to1(int row, int col) 
{ 
    return (row - 1) * n + col; 
} 

int binary(int find) 
{ 
    int low = 1, high = n*n, mid; 

    while(low <= high) 
    { 
     search_cnt++; 
     mid = (low + high)/2; 
     if(_1to2(mid) > find) 
      high = mid - 1; 
     else if(_1to2(mid) < find) 
      low = mid + 1; 
     else 
     { 
      printf("search_cnt = %d, ", search_cnt); 
      return mid; 
     } 
    } 

    return -1; 
} 

int main() 
{ 
    int cnt = 1; 
    search_cnt = 0; 

    arr.resize(n+1); 
    for(int i = 0; i <= n; i++) 
     arr[i].resize(n+1); 

    for(int i = 1; i <= n; i++) 
     for(int j = 1; j <= n; j++) 
      arr[i][j] = cnt++; 

    for(int i = 1; i <= n*n; i++) 
    { 
     printf("searching pos = %d \n", binary(i)); 
     search_cnt = 0; 
    } 

    return 0; 
} 
+1

二进制搜索对总订单起作用。具有排序行和列的二维数组并不完全排序。你打算如何使用二分查找?我想看看伪代码。 – Gene

+0

如果矩阵按行到列和矩阵单元开始排序(1,1),我可以认为每个单元(arr [y] [x])是1d数组(arr [p],p =(x-1)* n + y)。 – jingbe