leetcode刷题笔记-binary search

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Sengo_GWU/article/details/82833587

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
        
        return self.helper(0, len(matrix)-1, matrix, target)  
    
    def helper(self, start, end, matrix, target):
      
        if start == end:
            for n in matrix[start]:
                if n == target:
                    return True
            else:
                return False
        
        midRow = (end + start)/2
        if not matrix[midRow]: return False
        mid = matrix[midRow][-1]  
        if target > mid:
            return self.helper(midRow+1, end, matrix, target)
        else:
            return self.helper(start, midRow, matrix, target)

240. Search a 2D Matrix II

We start search the matrix from top right corner, initialize the current position to top right corner, if the target is greater than the value in current position, then the target can not be in entire row of current position because the row is sorted, if the target is less than the value in current position, then the target can not in the entire column because the column is sorted too. We can rule out one row or one column each time, so the time complexity is O(m+n).

class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if not matrix:
            return False
        
        row, col = len(matrix)-1, len(matrix[0])-1
        i, j = 0, col
        
        while 0 <= i <= row and 0 <= j <= col:
            if matrix[i][j] > target:
                j -= 1
            elif matrix[i][j] < target:
                i += 1
            else:
                return True
        return False

猜你喜欢

转载自blog.csdn.net/Sengo_GWU/article/details/82833587
今日推荐