74. Search a 2D Matrix
2016-07-28 16:45
169 查看
Problem: https://leetcode.com/problems/search-a-2d-matrix/
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
Thought:
search last row , last column and the left matrix (I didn't consider the second property)
If I consider the second property, search for row then search the row would be much better.(O(log(mn)))
Code C++:
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
Thought:
search last row , last column and the left matrix (I didn't consider the second property)
If I consider the second property, search for row then search the row would be much better.(O(log(mn)))
Code C++:
class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { if (matrix.size() < 1) { return false; } int m = matrix.size(), n = matrix[0].size(); if (target > matrix[m - 1][n - 1]) { return false; } else if (target == matrix[m - 1][n - 1]) { return true; } if (m == 1) { return binary_search(matrix[0].begin(), matrix[0].end(), target); } if (n == 1) { vector<int> column; for (int i = 0; i < matrix.size(); i++) { column.push_back(matrix[i][0]); } return binary_search(column.begin(), column.end(), target); } vector<vector<int>> corner; vector<int> row; vector<int> column; for (int i = 0; i < m - 1; i++) { vector<int> temp; for (int j = 0; j < n - 1; j++) { temp.push_back(matrix[i][j]); } corner.push_back(temp); } for (int i = 0; i < n - 1; i++) { row.push_back(matrix[m - 1][i]); } for (int i = 0; i < m - 1; i++) { column.push_back(matrix[i][n - 1]); } return binary_search(row.begin(), row.end(), target) || binary_search(column.begin(), column.end(), target) || searchMatrix(corner, target); } };
相关文章推荐
- javascript eval和JSON之间的联系
- linux使用grep和find查找内容
- 分布式模式之Broker模式
- 让你的Python代码更加pythonic
- 【HEVC帧间预测论文】P1.4 Motion Vectors Merging: Low Complexity Prediction Unit Decision
- Centos 7 文件和目录管理
- 获取网络状态
- linux如何关闭selinux?
- jquery 取值赋值
- Linux wifi 破解
- php webservice服务端和客户端的实现
- Java基础面试题之Singleton模式
- 字符集
- Windows8.1打开程序报 api-ms-win-crt-heap-l1-1-0.dll 错误的解决办法
- 其它网页可以上网,IE浏览器打不开网页的解决办法
- 数学
- Cesium应用篇:3控件(5)CesiumInspector
- 详解web.xml中元素的加载顺序
- 【HEVC帧间预测论文】P1.3 Fast Inter-Frame Prediction Algorithm of HEVC Based on Graphic Information
- 代理模式(Proxy)一 静态代理