We have an n x n matrix, where every row and column is sorted in increasing order.
Given a number x, how to decide whether this x is in the matrix, better than O(n) complexity?
We have an n x n matrix, where every row and column is sorted in increasing order.
Given a number x, how to decide whether this x is in the matrix, better than O(n) complexity?
I think that just use binary search.
Time complexity of Binary search is O(log(n)).
So, in case n x n matrix, time complexity is O(log(n^2)) = O(2log(n)).
It is better than O(n).
-----(edit) / this is my cpp code.
#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;
}