74. Search a 2D Matrix

 
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        // sanity check 
        if(matrix == null || matrix.length == 0 ){
            return false;
            
        }
        
        int n = matrix.length;
        int m = matrix[0].length;
        
        int left = 0;
        int right = n * m - 1;
        while(left <= right){ // example 1 
            int mid = left + (right - left) / 2;
            int row = mid / m;
            int col = mid % m; // this mid is also index, so no need to mid % m - 1 
            if(matrix[row][col] == target) return true;
            if(matrix[row][col] < target){
                left = mid + 1;
            }else{
                right = mid - 1;
            }
            
        }
        return false;
        
    }
}

 

 

 

Use binary search.

 

n * m matrix convert to an array => matrix[x][y] => a[x * m + y]

 

an array convert to n * m matrix => a[x] =>matrix[x / m][x % m];

 

 

 

 

 

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.

Example 1:

Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 3
Output: true

Example 2:

Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 13
Output: false

posted on 2018-07-18 08:23  猪猪&#128055;  阅读(93)  评论(0)    收藏  举报

导航