74. Search a 2D Matrix
来源:互联网 发布:ehshig软件 编辑:程序博客网 时间:2024/06/03 06:47
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
.
由题意得,是要在m * n的矩阵里面找到给出的target值,而且是矩阵是排好序的,所以我的做法是,先确定target值留在哪一行,然后对行进行二分查找。其实还可以有更好的做法,是直接对行和列进行二分查找,那我打算把两种做法都写出来,第一种的时间复杂度是O(m + logn)
Code(LeetCode运行9ms)
class Solution {public: bool searchMatrix(vector<vector<int>>& matrix, int target) { if (matrix.size() == 0 || matrix[0].size() == 0) { return false; } int col = matrix[0].size(); int row = matrix.size(); for (int i = 0; i < row; i++) { if (target == matrix[i][0] || target == matrix[i][col - 1]) { return true; } if (target > matrix[i][0] && target < matrix[i][col - 1]) { return GaoMian(matrix[i], target, 0, col - 1); } } return false; } bool GaoMian(vector<int> nums, int target, int start, int end) { if (start > end) { return false; } int mid = start + (end - start) / 2; if (target == nums[mid]) { return true; } else if (target > nums[mid]) { return GaoMian(nums, target, mid + 1, end); } else { return GaoMian(nums, target, start, mid - 1); } }};
bool searchMatrix(vector<vector<int>>& matrix, int target) { if (matrix.empty()) { return false; } int col = matrix[0].size(); int row = matrix.size(); int start = 0, end = col * row; while (start < end) { int mid = start + (end - start) / 2; if (matrix[mid / col][mid % col] == target) { return true; } else if (matrix[mid / col][mid % col] > target) { end = mid; } else { start = mid + 1; } } return false; }
阅读全文
0 0
- LeetCode 74. Search a 2D Matrix
- [LeetCode]74.Search a 2D Matrix
- LeetCode --- 74. Search a 2D Matrix
- [Leetcode] 74. Search a 2D Matrix
- [leetcode] 74.Search a 2D Matrix
- 74. Search a 2D Matrix
- 74. Search a 2D Matrix
- Leetcode 74. Search a 2D Matrix
- [LeetCode]74. Search a 2D Matrix
- 74. Search a 2D Matrix LeetCode
- 74. Search a 2D Matrix
- 74. Search a 2D Matrix
- 74. Search a 2D Matrix
- [LeetCode]74. Search a 2D Matrix
- [LeetCode]74. Search a 2D Matrix
- 74. Search a 2D Matrix
- 74. Search a 2D Matrix
- leetcode 74. Search a 2D Matrix
- MIME协议在邮件中的应用详解
- Android Studio导入外部源码(用Android Studio写的)
- PAT 1003.我要通过!
- Tomcat的安装和配置(Windows)
- 抢票系统的简单实现
- 74. Search a 2D Matrix
- 4.文件和目录
- RevitAPI之创建一个面积【比目鱼原创】
- 在Linux上安装Oracle数据库 11g
- 第 1 章:Python 概述
- JVM内存分配和回收策略
- Keepalived高可用httpd,以及日志重定向
- Spring表达式基础(Spring Expression Language)
- tensor.get_shape()