码迷,mamicode.com
首页 > 编程语言 > 详细

Search a 2D Matrix【python】

时间:2014-08-28 11:24:19      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   div   log   sp   line   

class Solution:
    # @param matrix, a list of lists of integers
    # @param target, an integer
    # @return a boolean
    def searchMatrix(self, matrix, target):
        n=len(matrix)
        m=len(matrix[0])
        if target>matrix[n-1][m-1] or target<matrix[0][0]:
            return False
        head = 0
        end = n-1
        mid = (end+head)//2
        while mid>head and mid <end:
            if target<matrix[mid][0]: end=mid
            else: head=mid
            mid= (end+head)//2
        keyline=mid
        if target>matrix[keyline][m-1]: keyline+=1
        head = 0
        end = m-1
        mid = (end+head)//2
        while mid>=head and mid <end:
            if target<=matrix[keyline][mid]: end=mid
            else: head=mid+1
            mid= (end+head)//2        
        return target==matrix[keyline][mid]
   
if __name__==__main__:
    s=Solution()
    m=[[1,2,3],[4,5,6],[7,8,9]]
    print(s.searchMatrix(m,3))

OJ runtime :224 ms

Search a 2D Matrix【python】

标签:style   blog   color   io   ar   div   log   sp   line   

原文地址:http://www.cnblogs.com/iois/p/3940958.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!