Write an efficient algorithm that searches for a value in an m x 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.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
Given target =
3
, return true
.
Solution: binary search
Because of the matrix's special features, the matrix can be considered as a sorted array. Your goal is to find one element in this sorted array by using binary search.
midValue 的位置: 行数是position/columns,而列数是position%columns.
Run time complexity is O(logn), constant space.public class Solution { public boolean searchMatrix(int[][] matrix, int target) { if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return false; int i = matrix[0].length; int j = matrix.length; int start = 0, end = i * j -1; while(start <= end) { int mid = (end + start) / 2; int midValue = matrix[mid/i][mid%i]; if(target == midValue) return true; if(target < midValue) end = mid - 1; else start = mid + 1; } return false; } }
No comments:
Post a Comment