The algorithm Java implementation of sword-finger offer
topic:
In a two-dimensional array, each row is sorted in ascending order from left to right , and each column is sorted in ascending order from top to bottom. Please complete a function, enter such a two-dimensional array and an integer to determine whether the array contains the function.
For example, the following two-dimensional array is each row, each column is an ascending sort. Returns True if the number 7 is found in this array, or FALSE if you look for an array of 5, because the array does not contain the number.
1 2 8 9
2 4 9 12
4 7 10 13
6 8 11 15
When we solve a problem, a very effective way is to start from a specific problem, through the analysis of simple concrete examples, try to find the general law.
Package com.ynu.www.offer; public class Findfrommatrix {private static int[][] Sample = new int[][] {{1, 2, 8, 9}, {2, 4,
9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15}}; public static void Printsample () {to (int i = 0; i < sample.length; i++) {for (int j = 0; j < Sample[i].length;
J + +) {System.out.print (Sample[i][j] + "");
} System.out.println (); } public static Boolean Getvaluefrommatrix (int[][] sample, int rows, int columns, int num)
{Boolean found = false;
if (sample!= null && rows > 0 && columns > 0) {int row = 0;
int column = Columns-1;
while (Row < rows && column >= 0) {int tempvalue = Sample[row][column];
if (num > Tempvalue) {++row; } ElSe if (num < tempvalue) {--column;
else {found = true;
Break
}} return found;
public static void Main (string[] args) {printsample ();
System.out.println (Getvaluefrommatrix (Sample, 4, 4, 7)); }
}
Based on the analysis, each time we pick the upper-right digits of the array lookup range, we can also select the lower-left digits, but we cannot select the upper-left or lower-right corners because we cannot narrow the lookup range.