Given a matrix in which each row and each column is sorted, write a method to find an element in it.
其实很简单,关键在于搜索的起始点要在矩阵的右上角。
这样做的好处是方便查找。如果比目标x小,那么row++;如果比x大,则col--;
#include <iostream>
using namespace std;
int* search_matrix(int matrix[][4], int n, int m, int x)
{
int i=0,j=m-1;
int *ans = new int[2];
while(i<n && m>=0)
{
if(matrix[i][j]==x)
{
ans[0]=i;
ans[1]=j;
return ans;
}
else if(matrix[i][j] < x)
i++;
else
j--;
}
return ans;
}
int main()
{
int matrix[4][4]=
{
1,2,3,4,
5,6,7,8,
9,10,11,12,
13,14,15,16
};
int *ans = new int[2];
ans=search_matrix(matrix, 4, 4, 8);
cout <<"X: " <<ans[0] <<" , Y: " <<ans[1]<<endl;
free(ans);
return 0;
}