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 in ascending from left to right.
- Integers in each column is sorted in ascending from top to bottom.
For example,
Consider the following matrix:
[[1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17 , [+], [approx., +, +]]
given target = 5 , Return true .
Given Target = 20 , return false .
[Idea]o (m+n) complexity, starting from the top of the search. Because the matrix is ordered, you can narrow the scope based on the size relationship.
Class Solution {public: bool Searchmatrix (vector<vector<int>>& matrix, int target) { int m = Matrix.size (); int n = matrix[0].size (); int i = 0; int j = n-1; while (i>=0 && j>=0 && i<m &&j<n) { if (target = = Matrix[i][j]) return true;< C8/>if (Target>matrix[i][j]) { i++; } else j--; } return false; }};
O (MLOGN) searches each row for two points.
Class Solution {public: bool Searchmatrix (vector<vector<int>>& matrix, int target) { int m = Matrix.size (); int n = matrix[0].size (); for (int i=0; i<m; ++i) { if (matrix[i][0]<=target && matrix[i][n-1]>=target) { if ( Searchvector (matrix[i],target)) return true; } } return false; } BOOL Searchvector (vector<int>& v, int target) { int left = 0, right = v.size ()-1; while (left <= right) { int mid = left + (right-left)/2; if (v[mid] = = target) return true; if (V[mid] < target) Left = mid + 1; else right = mid-1; } return false; } };
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Leetcode]search a 2D Matrix II