Leetcode之Search a 2D Matrix 问题

来源:互联网 发布:mac安装ps软件教程 编辑:程序博客网 时间:2024/05/19 00:53

问题描述:

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

1.Integers in each row are sorted from left to right

2.The first integer of each row is greater than the last integer of the previous row.

示例:

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

Given target = 3, return true.

问题来源:Search a 2D Matrix (详细地址:https://leetcode.com/problems/search-a-2d-matrix/description/)

思路分析:我相信大部分人和我一样,拿到这道题的时候,充满疑问。还有这种矩阵?还能有这种操作?这一看就是设定好的数组嘛,那它究竟是什么用意呢?考查的啥知识点呢?对二分查找熟悉的人一眼就看出来了,它设定的两个假设条件就是为了让我们构造一个有序数组,那么下面就牵涉到二维数组和一维数组之间的转化了,这个在前面也讲过了,今天再次罗列一下:

                   1)一个二维数组n * m转化为一维数组:
          matrix[x][y]-->a[x * m + y];
          2)一维数组转化为二维数组n * m:
          a[x]-->matrix[a / m][a % m]

接下来就是二分查找了,这都是老套路了,也没啥好讲的了吧。

代码:


原创粉丝点击