[LeetCode#74]Search a 2D Matrix

The problem:

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.

Solution1:

public class Solution {

    public boolean searchMatrix(int[][] matrix, int target) {

        if (matrix == null || matrix.length == 0) //sterotype checking

            return false;

        int low = 0;

        int high = matrix.length - 1;

        int mid = -1;

        int row_index = -1;

        while (low <= high) { //search the row that may contain target

            mid = (low + high) / 2;

            if (matrix[mid][0] == target) {

                return true;

            } else if (matrix[mid][0] < target) {

                low = mid + 1;

            } else {

                high = mid - 1;

            }

        }

        /*a little skill: when exit while loop

        1. array[low] is the element just bigger than target;

        2. array[high] is th element just smaller than target.

        

        if (matrix[mid][0] > target) // the row that may contain target (mid + 1 is the possible to insert)

            row_index = mid - 1;

        else 

            row_index = mid; 

        */

        row_index = high;

        if (row_index < 0) //the target is even smaller than the smallest element in the matrix(first element)

            return false;

        low = 0;

        high = matrix[0].length - 1;

        mid = -1;

        while (low <= high) { //serach the target in the possible row

            mid = (low + high) / 2;

            if (matrix[row_index][mid] == target) {

                return true;

            } else if (matrix[row_index][mid] < target) {

                low = mid + 1;

            } else {

                high = mid - 1;

            }

        }

        return false;

    }

}

Solution2:

public class Solution {

    public boolean searchMatrix(int[][] matrix, int target) {

        int row_count = matrix.length;

        int column_count = matrix[0].length;

        if (matrix == null || matrix[0][0] > target || matrix[row_count-1][column_count-1] < target)

            return false;

        int i = 0;

        int j = column_count - 1;

        while (i <= row_count-1 && j >= 0) {

            if (matrix[i][j] == target)

                return true;

            else if (matrix[i][j] < target)

                i++;

            else

                j--;

        }

        return false;

    }

}

 

你可能感兴趣的:(LeetCode)