【leetcode】第74题 Search a 2D Matrix 题目+解析+JAVA代码

来源:互联网 发布:摄乎大国之间的句式 编辑:程序博客网 时间:2024/06/05 10:21

【题目】

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 boolean searchMatrix(int[][] matrix, int target) {        int m=matrix.length;        if(m==0) return false;        int n = matrix[0].length;        int left=0,right=m*n-1;        while(left<=right){            int mid=(left+right)/2;            if(target==matrix[mid/n][mid%n])                return true;            else if(target>matrix[mid/n][mid%n])                left=mid+1;            else                right=mid-1;        }        return false;    }


原创粉丝点击