74. Search a 2D Matrix

来源:互联网 发布:python换两行 编辑:程序博客网 时间:2024/06/08 01:55

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.

思路:就是两次二分查找的过程,第一次二分查找确定在哪一行,第二次二分查找确定有没有

代码如下(已通过leetcode)

public class Solution {
   public boolean searchMatrix(int[][] matrix, int target) {
      
        int row=findrow(matrix, target, 0, matrix.length-1);
        //System.out.println("第"+row+"行");
        if(findit(matrix, row, target, 0, matrix[row].length-1)==Integer.MIN_VALUE) return false;
        else { 
        //int position=findit(matrix, row, target, 0, matrix[row].length-1);
        //System.out.println("第"+row+"行"+"第"+position+"位");
        return true;
        }
       
   }
   
   public int findrow(int[][] matrix,int target,int low,int high) {
    while(low<=high) {
    if(matrix[low][matrix[low].length-1]<target) low++;
    else {
    return low;
    }
    }
   
    return low-1;
   
   
   
   
   }
   
   public int findit(int[][] matrix,int row,int target,int low,int high) {
    if(low>high) return Integer.MIN_VALUE;
    int mid=(low+high)/2;
    if(matrix[row][mid]==target) return mid;
    else {
    if(matrix[row][mid]>target){
    high=mid-1;
    } else {
    low=mid+1;
    }
    return findit(matrix, row, target, low, high);
    }
   }
}

0 0