My two binary search solution


  • 0
    S
    public boolean searchMatrix(int[][] matrix, int target) {
        int i = binarySearch2(matrix, target);
    	return binarySearch(matrix[i], target);
    }
    private boolean binarySearch(int[] array, int target) {
    	int i = 0;
    	int j = array.length - 1;
    	int mid;
    	while (i <= j) {
    		mid = (j - i) / 2 + i;
    		if (array[mid] == target)
    			return true;
    		else if (array[mid] < target)
    			i = mid + 1;
    		else j = mid - 1;
    	}
    	return false;
    }
    private int binarySearch2(int[][] array, int target) {
    	int i = 0;
    	int j = array.length - 1;
    	int mid = 0;
    	while (i <= j) {
    		mid = (j-i)/2 + i;
    		if (target < array[mid][0]) {
    			j = mid - 1;
    		}
    		else if (target > array[mid][0]) {
    			i = mid + 1;
    		}
    		else return mid;
    	}
    	return j >= 0 ? j : 0;
    }

Log in to reply
 

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