Search a 2D Matrix
Write an efficient algorithm that searches for a value in an mx n matrix.
This matrix has the following properties:
- Integers in each row are sorted from left to right.
- The first integer of each row is greater than the last integer of the previous row.
Example
Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3
, return true
.
分析
首先想到的是将二维坐标转换为一维
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | public class Solution { /** * @param matrix, a list of lists of integers * @param target, an integer * @return a boolean, indicate whether matrix contains target */ public boolean searchMatrix( int [][] matrix, int target) { // write your code here if (matrix == null || matrix.length == 0 || matrix[ 0 ].length == 0 ) return false ; int row = matrix.length; int col = matrix[ 0 ].length; int left = 0 , right = row * col - 1 ; while (left < right){ int mid = left + (right - left) / 2 ; int i = mid / col; int j = mid % col; if (matrix[i][j] < target){ left = mid + 1 ; } else { right = mid; } } if (matrix[left / col][left % col] == target) return true ; else return false ; } } |