【LeetCode热题100】--74.搜索二维矩阵

74.搜索二维矩阵

【LeetCode热题100】--74.搜索二维矩阵_第1张图片

按行搜索,使用二分查找

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        for(int[] row : matrix){
            int index = search(row,target);
            if(index >= 0){
                return true;
            }
        }
        return false;
    }

    public int search(int[] nums,int target){
        int low = 0,high = nums.length -1;
        while(low <= high){
            int mid = (low + high) / 2;
            if(nums[mid] == target){
                return mid;
            }
            if(target > nums[mid]){
                low = mid + 1;
            }
            if(target < nums[mid]){
                high = mid - 1;
            }
        }
        return -1;
    } 
}

你可能感兴趣的:(LeetCode,leetcode,算法)