Fortune left-law basis class3- find the title number 9 in the ranks are sorted matrix
1. Topic
[Title] Given a matrix of M * N matrix integer and an integer num, each row and each column of the matrix are sorted. Implement a function, K is determined whether the matrix. For example: {{1,3,5,6}, {2,5,7,9}, {4,6,8,10}} If num is 7, returns true; if K is 11, returns false.
[Requirements] time complexity of O (N + M), additional space complexity is O (1).
2. Analysis
Under normal circumstances only O (N + M), then we need to find a starting number can not be reached from the complexity of a set of numbers from a set of questions and data status question is asked to find a solution ideas.
This problem can be from the data situation known each row of each column are ranked good, then omit unnecessary part of traversal. As shown below, it is assumed traversing from the top right corner, 6> 4, 6 due to the row and column location are sorted, so the lower 9,10 6 4 impossible to find because they are larger than 6, Nature greater than 4. Thus eliminating unnecessary process.
So the idea of this question is as follows:
(1) Find the upper right corner, if the current number is greater than num, the current number continues to look to the left; if the current number is less than num, continue down the current number lookup. If the current count is equal to true return;
(2) Since only look forward and downward to the left, then traverse the condition that the number of the current scope of the entire matrix, start from the top right, then, thatcur_col >= 0 && cur_row <= M -1
3. core code
Find in the arr num, cur_col is a longitudinal, cur_row transverse coordinates.
bool findnum(int arr[][N],int num)
{
int cur_col = N - 1;
int cur_row = 0;
while(cur_col >= 0 && cur_row <= M -1)
{
if(arr[cur_row][cur_col] < num)
{
cur_row++;
}
else if(arr[cur_row][cur_col] > num)
{
cur_col--;
}
else
return true;
}
return false;
}
4. The complete code
#include<iostream>
#define M 3
#define N 4
using namespace std;
bool findnum(int arr[][N],int num)
{
int cur_col = N - 1;
int cur_row = 0;
while(cur_col >= 0 && cur_row <= M -1)
{
if(arr[cur_row][cur_col] < num)
{
cur_row++;
}
else if(arr[cur_row][cur_col] > num)
{
cur_col--;
}
else
return true;
}
return false;
}
int main()
{
int arr[M][N] = {{1,3,5,6},{2,5,7,9},{4,6,8,10}};
cout<<findnum(arr,4)<<endl;
system("pause");
return 0;
}
5. The output
From the start traversing 6, passes through the 5,3,5,2, and finally found 4, returns true, print 1.