title :
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.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [Ten, One,], [23, 30, 34, 50]]
Given target = 3
, return true
.
Test Instructions: give a m*n matrix, wherein the matrix is characterized by: (1) Each line from small to large ordered (2) each row of the first digit is larger than the number of the previous row, the need to write a matrix to determine whether an element exists in the algorithm. Because of the characteristics of this matrix, we can think of this matrix directly as a one-dimensional array newarray, with a length of m*n, where newarray[x] can correspond to the number of matrix[x/columns][x% columns of the matrix]. Then use binary search directly to NewArray. It is important to note that when the matrix is empty, you need to return false directly.
Code:
public class Solution {public boolean Searchmatrix (int[][] matrix, int target) {if (matrix.length==0) {return false;} int col=matrix[0].length;//array number of columns int row=matrix.length;//array rows int[] newarray=new int[row*col];// A two-dimensional array is placed in a one-dimensional, newarray[i] corresponds to a two-dimensional array of matrix[i/n][i%n] return BinarySearch (Matrix,newarray,target); } public boolean BinarySearch (int[][] matrix,int[] newarray,int target) {int length=newarray.length;int col=matrix[0]. length;//array of columns int low=0;int high=length-1;while (low<=high) {int mid= (Low+high)/2;if (matrix[mid/col][mid%col]< Target) {low=mid+1;} else if (matrix[mid/col][mid%col]>target) {high=mid-1;} Else{//system.out.println ("Find:" +target); return true;}} System.out.println ("Not find:" +target); return false;}}
Leetcode 74.Search a 2D Matrix Java