Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
Given target = 3
, return true
.
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { // Start typing your Java solution below // DO NOT write main() function int row = matrix.length; int col = matrix[0].length; if(row == 0 || col == 0 )return false; int low = 0 ; int high = row*col -1; while(low <= high){ int mid = low + (high - low)/2; if(matrix[mid/col][mid%col] == target) return true; else if(matrix[mid/col][mid%col] > target){ high = mid -1; } else{ low = mid +1; } } return false; } }
learned: matrix[mid/col][mid%col]