074 Search a 2D Matrix

一开始的想法是先确定行,在确定是否在这一行中 方法如下

class Solution:
    # @param {integer[][]} matrix
    # @param {integer} target
    # @return {boolean}
    def searchMatrix(self, matrix, target):
        m = len(matrix)
        if m == 0:
            return False
        if m == 1:
            return self.help(matrix[0], target)
        a = matrix[m/2][0]
        if a == target:
            return True
        elif a < target:
            return self.searchMatrix(matrix[m/2:], target)
        else:
            return self.searchMatrix(matrix[:m/2], target)

    def help(self, l, target):
        if l[0] > target or l[-1] < target:
            return False
        left = 0
        right = len(l)-1
        while left <= right:
            mid = (left + right) / 2
            if l[mid] == target:
                return True
            elif l[mid] > target:
                right = mid - 1
            else:
                left = mid + 1
        return False

 

后来想想本来就是二分,虽然有不同的行和列, 但其实可以看做一维的下标,方法如下。 与以上方法运时间差不多,因此并没有太大优点 最终复杂度都是 O(m+n)

class Solution:
    # @param {integer[][]} matrix
    # @param {integer} target
    # @return {boolean}
    def searchMatrix(self, matrix, target):
        m = len(matrix)
        if m == 0:
            return False
        n = len(matrix[0])
        left, right = 0, m*n-1
        while left <= right:
            mid = (left + right)/2
            a = matrix[mid/n][mid%n]
            if a == target:
                return True
            elif a < target:
                left = mid + 1
            else:
                right = mid - 1
        return False

 

posted @ 2015-07-08 03:30  dapanshe  阅读(114)  评论(0编辑  收藏  举报