Search In Sorted Matrix I in Python(Binary Search)

Given a 2D matrix that contains integers only, which each row is sorted in an ascending order. The first element of next row is larger than (or equal to) the last element of previous row.

Given a target number, returning the position that the target locates within the matrix. If the target number does not exist in the matrix, return {-1, -1}.

Assumptions:

The given matrix is not null, and has size of N * M, where N >= 0 and M >= 0.

Examples:

matrix = { {1, 2, 3}, {4, 5, 7}, {8, 9, 10} }

target = 7, return {1, 2}

target = 6, return {-1, -1} to represent the target number does not exist in the matrix.

class Solution(object):
  def search(self, matrix, target):
    n = len(matrix)
    m = len(matrix[0])
    left = 0
    right = m*n - 1
    res = [-1,-1]
    while left <= right :
      mid = (left + right)/2
      rowindex = mid/m
      colindex = mid%m
      if matrix[rowindex][colindex] == target:
        res[0] = rowindex
        res[1] = colindex
        return res
      elif matrix[rowindex][colindex] < target:
        left = mid + 1
      else: right = mid - 1
    return res
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,179评论 0 10
  • 文/一叶苦艾 上一章 方燕是李涛在学生会活动室认识的。那天李涛利用周末在学生会活动室起草书法大赛的活动章程。门外传...
    一叶苦艾阅读 1,864评论 1 2
  • 返回目录 wx:for在组件上使用 wx:for 控制属性绑定一个数组,即可使用数组中各项的数据重复渲染该组件。默...
    LYSNote阅读 10,698评论 1 0
  • 叱咤风云的岁月, 雪上行马的今夜。 一个人两世风尘, 一匹马半生厮守。 一朝飞雪倾泻十载宇宙沧桑, 一颗冰心承载半...
    你予的暖阅读 1,846评论 0 0

友情链接更多精彩内容