Search a 2D Matrix
Total Accepted: 43629 submissions: 138231
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
.
Conventional train of thought, two times
BOOL Searchmatrix (vector<vector<int>>& matrix, int target) { if (Matrix.empty ()) return False ; Vector<int> Firstcol; for (auto V:matrix) firstcol.push_back (v[0]); if (Binary_search (Firstcol.begin (), Firstcol.end (), target)) return true; Vector<int>::iterator iter = Lower_bound (Firstcol.begin (), Firstcol.end (), target); int low = Iter-firstcol.begin (); for (int i = 0; i < low; i++) { if (Binary_search (Matrix[i].begin (), Matrix[i].end (), target)) return true; } return false; }
Opportunistic, there are potential bugs
BOOL Searchmatrix (vector<vector<int> >& matrix, int target) { int rows = Matrix.size (); if (rows = = 0) return false; int cols = Matrix[0].size (); int first = 0, last = rows * COLS-1; if (Target < matrix[0][0] | | target > MATRIX[ROWS-1][COLS-1]) return false; int mid, Val; Binary search while (first <=) { mid = first + (Last-first)/2; val = matrix[mid/cols][mid% cols]; if (Val > Target) Last = mid-1; else if (val = = target) return true; else First = mid + 1; } return false; }
Leetcode:search a 2D Matrix