码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode_28.搜索二维矩阵

时间:2017-12-12 12:17:15      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:lintcode   数据   算法   elf   高效   第一个   body   ram   code   

写出一个高效的算法来搜索 m × n矩阵中的值。

这个矩阵具有以下特性:

  • 每行中的整数从左到右是排序的。
  • 每行的第一个数大于上一行的最后一个整数

样例

考虑下列矩阵:

[
  [1, 3, 5, 7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

给出 target = 3,返回 true

class Solution:
    """
    @param: matrix: matrix, a list of lists of integers
    @param: target: An integer
    @return: a boolean, indicate whether matrix contains target
    """
    def searchMatrix(self, matrix, target):
        # write your code here

        for i in matrix:
            if i[-1] >= target:
                for x in i:
                    if x == target:
                        return True
                return False
        return False

行顺序遍历,再顺序找列。

也可以用二分搜索,看成一维向量做,不过好像效率更低一点,可能跟数据量有关。

九章参考:

class Solution:
    """
    @param matrix, a list of lists of integers
    @param target, an integer
    @return a boolean, indicate whether matrix contains target
    """
    def searchMatrix(self, matrix, target):
        if len(matrix) == 0:
            return False
            
        n, m = len(matrix), len(matrix[0])
        start, end = 0, n * m - 1
        while start + 1 < end:
            mid = (start + end) / 2
            x, y = mid / m, mid % m
            if matrix[x][y] < target:
                start = mid
            else:
                end = mid
        x, y = start / m, start % m
        if matrix[x][y] == target:
            return True
        
        x, y = end / m, end % m
        if matrix[x][y] == target:
            return True
        
        return False

 

lintcode_28.搜索二维矩阵

标签:lintcode   数据   算法   elf   高效   第一个   body   ram   code   

原文地址:http://www.cnblogs.com/zhangli-ncu/p/8026910.html

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