Question: https://oj.leetcode.com/problems/search-a-2d-matrix/
Question Name: Search a 2D Matrix
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class Solution: # @param matrix, a list of lists of integers # @param target, an integer # @return a boolean def searchMatrix(self, matrix, target): ''' Flatten the matrix into 1-dimension list. Then this question turns to be binary search question. ''' rowLen = len(matrix) colLen = len(matrix[0]) begin, end = 0, rowLen * colLen - 1 while begin <= end: mid = (begin + end) // 2 # Convert to 1D binary search question midCell = matrix[mid//colLen][mid%colLen] if midCell > target: end = mid - 1 elif midCell < target: begin = mid + 1 else: return True return False |