《算法分析与设计》Week 10
2017-06-02 21:26
579 查看
74. Search a 2D Matrix
Description:
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
Given target =
Solution:
一、题意理解
在一个m x n 的二维矩阵中做一个查找算法。矩阵有下面的特点
(1) 每一行从左到右是升序的。
(2) 每一行第一个数比上一行最后一个数要大。
二、分析
1、直接查找的方式是对每一行执行一个二分查找,时间复杂度为 O(mLog(n))
2、仔细看一下题目中矩阵的特点,发现其完全可以当做一个一维矩阵,只需要将每一行首位连接即可,连接后的一维矩阵就是一个升序的数组,可以执行二分茶盏,时间复杂度为O(Log(mn))。这里所说的连接也不是真正的连接,只需要将一维数组的下标转化到二位矩阵的坐标即可。
3、代码如下:
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int row = matrix.size();
if(row == 0)
return false;
int column = matrix[0].size();
if(column == 0)
return false;
int begin = 0, end = row * column - 1;
while(begin <= end)
{
int index = (begin + end) / 2;
int num = matrix[index / column][ index % column];
if(target == num)
return true;
else if(target < num)
end = index - 1;
else
begin = index + 1;
}
return false;
}
};
Description:
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
Given target =
3, return
true.
Solution:
一、题意理解
在一个m x n 的二维矩阵中做一个查找算法。矩阵有下面的特点
(1) 每一行从左到右是升序的。
(2) 每一行第一个数比上一行最后一个数要大。
二、分析
1、直接查找的方式是对每一行执行一个二分查找,时间复杂度为 O(mLog(n))
2、仔细看一下题目中矩阵的特点,发现其完全可以当做一个一维矩阵,只需要将每一行首位连接即可,连接后的一维矩阵就是一个升序的数组,可以执行二分茶盏,时间复杂度为O(Log(mn))。这里所说的连接也不是真正的连接,只需要将一维数组的下标转化到二位矩阵的坐标即可。
3、代码如下:
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int row = matrix.size();
if(row == 0)
return false;
int column = matrix[0].size();
if(column == 0)
return false;
int begin = 0, end = row * column - 1;
while(begin <= end)
{
int index = (begin + end) / 2;
int num = matrix[index / column][ index % column];
if(target == num)
return true;
else if(target < num)
end = index - 1;
else
begin = index + 1;
}
return false;
}
};
相关文章推荐
- 《算法分析与设计》Week 2
- Week 10:Large Scale Machine Learning课后习题解答
- Leetcode:215. Kth Largest Element in an Array (week 10)
- week 10 Java作业
- (补)week10
- Machine Learning - XVIII. Application Example Photo OCR应用实例-照片OCR(Week10)
- 团队项目M1展示成绩和Week 10分数
- leetcode week 10
- week 10
- week--10作业第一题,比较繁琐。-_-!
- Machine Learning(Andrew)Week10(下)
- 《算法分析与设计》Week 3
- 《算法分析与设计》Week 1
- Leetcode:23. Merge k Sorted Lists (week 10)
- Decode String_Week10
- 《算法分析与设计》Week 8
- 《算法分析与设计》Week 15
- week_10
- Week 10算法分析作业
- Machine Learning - XVII. Large Scale Machine Learning大规模机器学习 (Week 10)