74. Search a 2D Matrix

来源:互联网 发布:淘宝打印助手怎么样 编辑:程序博客网 时间:2024/04/28 13:31

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.

题意:给定一个二维数组,每一行从左到右递增,每一行的第一个元素比上一行最后一个元素大,求给定的target是否存在数组中。

仔细观察一下就能相到:虽然题目给定的是一个二维数组,但是实际上我们可以等价于一个升序排序的一维数组,这样一来使用二分查找就可以很容易解决此题;

代码:

public class Solution {    public boolean searchMatrix(int[][] matrix, int target) {        if(matrix.length == 0 || matrix[0].length == 0)            return false;        int rowlen = matrix.length;        int collen = matrix[0].length;        int start = 0;        int end = rowlen*collen-1;                while(start <= end){            int mid = (start+end)/2;            int midr = mid/collen;            int midc = mid%collen;            if(target == matrix[midr][midc])                return true;            if(target < matrix[midr][midc] )                end = mid-1;            else                start = mid+1;        }        return false;    }}