Topic:
Write an efficient algorithm, searches for a value in a m x n Matrix. This matrix has the following properties:
- Integers in each row is sorted from the left to the right.
- The first integer of each row was greater than the last integer of the previous row.
Package Leetcode;
public class Searcha2dmatrix {
Array Lookup: 1, good order (two points to find the premise) 2, two points to find!
public static Boolean Searchmatrix (int[][] matrix, int target) {
int m = 0;
while (m<=matrix.length-1) {
if (matrix[m][0]<=target&&matrix[m][matrix[0].length-1]>=target) {
return binary (matrix[m],0,matrix[0].length-1,target);
}else
m++;
}
return false;
}
public static Boolean binary (int nums[], int left,int right,int tar) {//Two-point lookup general algorithm
while (Right>=left) {
int mid = (right+left)/2;
if (nums[mid] = = tar) return true;
if (Nums[mid] >tar) return binary (Nums,left,mid-1,tar);
return binary (Nums,mid+1,right,tar);
}
return false;
}
public static void Main (string[] args) {
TODO auto-generated Method Stub
Int[][] a ={
{1, 3, 5, 7},
{10, 11, 16, 20},
{23, 30, 34, 50}
};
System.out.print (Searchmatrix (a,9));
}
}
Leetcode---Search a 2D Matrix