Share the code Just because it is concise


  • 0
    M

    The is code is no different with most of the ideas in the thread. Treat the matrix as an sorted array, the only thing that is different from binary search in an array is to calculate the coordination in the matrix.

    public class Solution {
        public boolean searchMatrix(int[][] matrix, int target) {
            int n = matrix.length;
            int m = matrix[0].length;
            int left = 0, right = n*m - 1;
            while (left <= right) {
                int mid = (right - left) / 2 + left;
                int j = mid % m; // calculate the column index
                int i = mid / m; // calculate the row index
                if (target == matrix[i][j]) {
                    return true;
                } else if (target > matrix[i][j]) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
            return false;
        }
    }
    

    Any comments are welcomed.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.