Title:
Given a n*m matrix and an integer k,matrix, each row and each column is well-ordered. Implement a function to determine if k is in the matrix.
For example:
0 1 2 5
2 3 4 7
4 4 4 8
5 7 7 9
Returns True if K is 7, or False if K is 6.
Requires a time complexity of O (n+m) with an O (1) Additional space complexity.
Ideas:
1. Start looking for (row=0,col=m-1) from the number of the top right corner of the matrix.
2. Compare the current number of matrix[row][col] with the K relationship:
- If it is equal to K, the description has been found, direct but true.
- If larger than K, because each column of the matrix is already ordered, so in the current number of columns, the number below the current number will be larger than K, then there is no need to continue to look in the Col column, so col--, repeat step 2.
- If it is smaller than k, because each row of the matrix is already ordered, so in the current number of rows, the number of the left of the current number will be larger than K, then there is no need to continue to find on row row, so row++, repeat step 2.
3. Returns False if no number is found that is equal to K if found out of bounds.
Public Static BooleanIscontains (int[] Matrix,intK) {intRow = 0; intCol = matrix[0].length-1; while(Row < matrix.length && col >-1) { if(Matrix[row][col] = =K) {return true; } Else if(Matrix[row][col] >K) {col--; } Else{row++; } } return false; }
[Algorithm] to find the number of matrices in which the rows and columns are well sequenced