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
.
Analysis: Test instructions to find the target value in a single MXN matrix. It is possible to determine the potential line of target values by the dichotomy method, and then use the second-division method to determine the possible location of target values in the row.
Time Complexity of O (LOGN+LOGM)
Code is as follows:
Class Solution {Public:bool Searchmatrix (vector<vector<int>>& matrix, int target) {int left=0; int Right=matrix.size ()-1; if (left! = right) {while (left <= right) {int mid=left + (right-left)/2; if (matrix[mid][0]<target) {left=mid+1; } else if (matrix[mid][0]>target) {right=mid-1; } else {return true; }}} if (Right==-1) {return false; } else{int row=right; int left=0; int Right=matrix[row].size ()-1; while (left<=right) {int mid=left + (right-left)/2; if (matrix[row][mid]<target) {left=mid+1; } else if (matrix[row][mid]>target) {right=mid-1; } else {return true; }} return false; } }};
Other ideas:
From the lower left corner, the element starts to traverse, and returns true if it is equal to the target value in each traversal, if the column is less than the right, and if it is greater then the row moves down. The time Complexity O (LOGN+LOGM) code is as follows:
Class Solution {public: bool Searchmatrix (vector<vector<int>>& matrix, int target) { int i= Matrix.size ()-1; int j=0; int m=matrix.size (); int n=matrix[0].size (); while (i>=0 && j<n) { if (Matrix[i][j] > target) { i--; } else if (matrix[i][j] = = target) { return true; } else{ j + +; } } return false; } };
Leetcode:search a 2D Matrix (array, binary lookup)