[LeetCode]74. Search a 2D Matrix

74. Search a 2D Matrix

题意:从二维数组中找到给定的目标值。

分析:需要注意的是,如果当前数比目标数要小,不能够意味着搜索的范围要从当前数的行和列数目开始,因为目标值有可能会在下一个行的左边列,题目中并没有要求当前行的最后一个数要比下一行的第一个数要小,所以你只能确定目标数在当前数和最后一个数的区间内时,才可以更新列从当前数所在列开始。

二分查找

class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if not matrix:
            return False
        start_row, end_row = 0, len(matrix) - 1
        start_col, end_col = 0, len(matrix[0]) - 1
        while start_row <= end_row and start_col <= end_col:
            mid_row, mid_col = (start_row + end_row) // 2, (start_col + end_col) // 2
            if matrix[mid_row][mid_col] == target:
                return True
            if matrix[mid_row][mid_col] < target:
                if matrix[mid_row][-1] < target:
                    start_row = mid_row + 1
                else:
                    start_col = mid_col + 1
            else:
                if matrix[mid_row][0] > target:
                    end_row = mid_row - 1
                else:
                    end_col = mid_col - 1
        return False

也可以先找到对应的行,然后使用bisect模块来进行确认。

class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if not matrix or not matrix[0]:
            return False
        j = 0
        row = -1
        for i in xrange(len(matrix)):
            if i == len(matrix) - 1:
                if target >= matrix[i][j]:
                    row = i
            else:
                if matrix[i][j] <= target and target < matrix[i+1][j]:
                    row = i
        if row == -1:
            return False
        if bisect.bisect_left(matrix[row], target) == len(matrix[0]):
            return False
        else:
            return matrix[row][bisect.bisect_left(matrix[row], target)] == target
posted @ 2017-08-20 03:46  banananana  阅读(156)  评论(0)    收藏  举报