Wednesday, June 17, 2015

Search a 2D Matrix | Leetcode

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.

---

Solution: Pretend that the 2D matrix is one linear array. Given an index i in the linear array, you can calculate the position of the corresponding element in the matrix. The row and column is given by: row = (i / cols), column = (i % cols). Perform an ordinary binary search to get the answer.
public class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int rows = matrix.length;
        int cols = matrix[0].length;
        int lo = 0;
        int hi = (rows * cols) - 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            int m = matrix[mid / cols][mid % cols];
            if (m == target) {
                return true;
            }
            if (m < target) {
                lo = mid + 1;
            } else {
                hi = mid - 1;
            }
        }
        return false;
    }
}

No comments: