Share my Java code, 0 ms, using binary search


  • 0
    I
    public class Solution {
        public boolean searchMatrix(int[][] matrix, int target) {
            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) {
                int mid = left + (right-left)/2;
                int x = mid/m;
                int y = mid%m;
                if (target == matrix[x][y]) return true;
                else if (target < matrix[x][y]) right = mid-1;
                else left = mid+1;
            }
            return false;
        }
    }
    

Log in to reply
 

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