My Java solution (accepted)


  • 0
    J

    Feedback welcome!

    public class Solution {
        public boolean searchMatrix(int[][] matrix, int target) {
        	int res = searchMatrix(matrix, 0, matrix.length * matrix[0].length, target);
            return res != -1;        
        }
        private int searchMatrix(int[][] matrix, int lo, int hi, int target) {    	
        	if (lo > hi) {
        		return -1;
        	}
        	int midIdx = (lo + hi) / 2;
        	int midVal = resolveValueFromPosition(matrix, midIdx);
        	if (target < midVal) {
        		return searchMatrix(matrix, lo, midIdx - 1, target); 
        	}
        	else if (target > midVal) {
        		return searchMatrix(matrix, midIdx + 1, hi, target);
        	}
        	else {
        		return midIdx;
        	}
        	
        }
        private int resolveValueFromPosition(int[][] matrix, int pos) {
        	int rows = matrix.length;
        	int cols = matrix[0].length;
        	int rowIdx = (pos / cols) % rows;
        	int colIdx = pos % cols;
        	return matrix[rowIdx][colIdx];
        }    
    }

Log in to reply
 

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