Search a 2D Matrix

来源:互联网 发布:原生js获取input框 编辑:程序博客网 时间:2024/06/11 16:48

Q:

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:

Time is O(m+n).

public class Solution {    public boolean searchMatrix(int[][] matrix, int target) {        if (matrix.length == 0 || matrix[0].length == 0 || matrix[0][0] > target)            return false;        int m = matrix.length;        int n = matrix[0].length;        int column = -1;        if (matrix[m-1][0] <= target)            column = m-1;        else {            int top = 0;            int bottom = m - 1;            while (top <= bottom) {                int mid = (top + bottom) / 2;                if (matrix[mid][0] == target)                    return true;                if (matrix[mid][0] < target && matrix[mid+1][0] > target) {                    column = mid;                    break;                }                if (matrix[mid][0] > target)                    bottom = mid - 1;                else                    top = mid + 1;            }        }                int left = 0;        int right = matrix[0].length - 1;        int row = 0;        while (left <= right) {            row = (left + right) / 2;            if (matrix[column][row] == target)                return true;            if (matrix[column][row] > target)                right = row - 1;            else                left = row + 1;        }        return false;    }}


0 0
原创粉丝点击