Thursday, December 11, 2014

Search 2D Matrix LeetCode (Important)

Very good question.
It can come with lots of follow up.

Step Wise method. I prefer this method. Easy to implement and very good for a quick solution during the interview.

public boolean searchMatrix(int[][] matrix, int target) {
        int rowLen = matrix.length;
        int colLen = matrix[0].length;
        int row = 0;
        int col = matrix[0].length-1;
        if (matrix[0][0] > target || matrix[rowLen-1][colLen-1] < target) return false;
     
        while (row < rowLen && col >= 0) {
            if (matrix[row][col] > target) {
                col--;
            } else if (matrix[row][col] < target) {
                row++;
            } else {
                return true;
            }
        }
        return false;
    }

Binary Search on row and column.
public boolean searchMatrix(int[][] matrix, int target) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int row = searchRow(matrix, 0, matrix.length, target);
        int result = Arrays.binarySearch(matrix[row], target);
        return result >= 0 ? true : false;
    }
 
    private int searchRow(int[][] matrix, int start, int end, int target) {
        int mid = (start + end)/2;
        if (start == mid) {
            return mid;
        }
        if (matrix[mid][0] <= target) {
            return searchRow(matrix, mid, end, target);
        } else {
            return searchRow(matrix, start, mid, target);
        }
    }

public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix==null || matrix.length==0 || matrix[0].length==0) return false;
        //Search the col
        int l=0;
        int r=matrix.length-1;
        while (l<=r) {
            int mid = (l+r)/2;
            if (matrix[mid][0] == target) return true;
            if (matrix[mid][0] > target) {
                r = mid - 1;
            } else {
                l = mid + 1;
            }
        }
        int row = r;
        if (row < 0) return false;
        //Search the row
        l=0;
        r=matrix[0].length-1;
        while (l<=r) {
            int mid = (l+r)/2;
            if (matrix[row][mid] == target) return true;
            if (matrix[row][mid] > target) {
                r = mid - 1;
            } else {
                l = mid + 1;
            }
        }
        return false;
    }

No comments:

Post a Comment