按行和列式排序矩阵搜索

时间:2017-04-06 23:04:44

标签: algorithm performance search

我们有一个n x n矩阵,其中每个行和列按递增顺序排序。

给定数字x,如何判断此x是否在矩阵中,优于O(n)复杂度?

1 个答案:

答案 0 :(得分:2)

我认为只需使用二分搜索。

二进制搜索的时间复杂度为O(log(n))。

因此,在n x 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;
}