[leetcode]Search a 2D Matrix

简单题。二分查找的应用。犯得错误是检查了数组下界0却忘了检查上界length。

public class Solution {

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

        // Start typing your Java solution below

        // DO NOT write main() function

        

        int m = matrix.length;

        if (m == 0) return false;

    	int n = matrix[0].length;

    	if (n == 0) return false;



    	if (target < matrix[0][0]) return false;

    	if (target > matrix[m-1][n-1]) return false;

    	

    	int left = 0; 

    	int right = m - 1;

    	while (left <= right) {

    		int mid = (left + right) / 2;

    		if (matrix[mid][0] == target) return true;

    		

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

    			right = mid - 1;

    		} else {

    			left = mid + 1;

    		}

    	}

    	

    	// at this time right < left

    	if (left < m && target > matrix[left][0]) {

    		return searchLine(matrix[left], target);

    	}

    	else if (right >= 0 && target > matrix[right][0]) {

    		return searchLine(matrix[right], target);

    	}

    	

    	return false;

    }  

    

    public boolean searchLine(int a[], int target)

    {

    	int left = 0; 

    	int right = a.length - 1;

    	while (left <= right) {

    		int mid = (left + right) / 2;

    		if (a[mid] == target) return true;

    		

    		if (a[mid] > target) {

    			right = mid - 1;

    		} else {

    			left = mid + 1;

    		}

    	}

    	return false;

    }

}

  

你可能感兴趣的:(LeetCode)