Search a 2D Matrix

来源:互联网 发布:最新网络词语 编辑:程序博客网 时间:2024/06/05 07:54

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
查找有序二维数组  依次确定其行和列  代码如下:
public class Solution {    public boolean searchMatrix(int[][] matrix, int target) {        int high=matrix.length;        int width=matrix[0].length;        int left=0;        int right=high-1;        int midh=0;        int midw=0;        int flag=0;        while(left<right){            midh=(left+right)/2;            if(matrix[midh][0]<=target){                if(matrix[midh][0]>=target){                  flag=1;                  break;                  }                else left=midh+1;            }            else{                right=midh-1;            }        }        if(flag==0)midh=left;        left=0;        right=width-1;        flag=0;        while(left<right){            midw=(left+right)/2;            if(matrix[midh][midw]==target){                flag=1;            break;            }            if(matrix[midh][midw]>target){                right=midw-1;            }else{                left=midw+1;            }        }        if(flag==0)midw=left;        if(matrix[midh][midw]==target) return true;        else return false;    }}


0 0
原创粉丝点击