Directory
1 Problem Description
2 Solutions
2.1 Positioning Method
1 problem description
in a two-dimensional array of M row n columns, each row is arranged in ascending order from left to right, and each column is arranged in ascending order from top to bottom. Now that you have entered such a two-dimensional array and an integer, complete a function that determines whether the array contains the integer.
2 Solutions
2.1 Positioning method
the time complexity of the algorithm below is O (M + N), space complexity is O (1).
The specific code is as follows:
Package Com.liuzhen.practice; Public classMain { PublicBoolean Youngmatrix (int[] A,intkey) { inti =0, j = a[0].length-1; inttemp =A[i][j]; while(true) { if(temp = =key) { return true; } Else if(Temp < key && I < a.length-1) {Temp= a[++i] [j]; } Else if(Temp > key && J >0) {Temp= a[i][--J]; } Else { return false; } } } Public Static voidMain (string[] args) {main test=NewMain (); int[] A = {{1,2,8,9},{2,4,9, A},{4,7,Ten, -},{6,8, One, the}}; if(Test. Youngmatrix (A,6) ) System. out. println ("The matrix A contains element 6"); ElseSystem. out. println ("element 6 is not included in matrix a"); if(Test. Youngmatrix (A,5) ) System. out. println ("The matrix A contains element 5"); ElseSystem. out. println ("element 5 is not included in matrix a"); }}
Operation Result:
Matrix A contains element 6 matrix A does not contain element 5
Resources:
1."Programming method interview and algorithmic experience" July
Algorithm Note _130: Lookup of row and column increment matrices (Java)