Question:
-
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 .
- Idea:
Think of the matrix as an array of processors.
- Code:
BOOL Searchmatrix (int** matrix, int matrixrowsize, int matrixcolsize, int target) { int low = 0, High=matrixrowsize*ma trixColSize-1; int mid; while (low <= high) { mid = low + (high-low)/2,//avoid to buffer overflow. if (Matrix[mid/matrixcolsize][mid%matrixcolsize] < target) Low = mid + 1; else if (Matrix[mid/matrixcolsize][mid%matrixcolsize] > target) high = Mid-1; else return true; } return false;}
[Leetcode] Search a 2D Matrix