LeetCode OJ 之 Search a 2D Matrix (二维矩阵的搜索)
来源:互联网 发布:卖家网wish数据 编辑:程序博客网 时间:2024/06/08 08:43
题目:
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.
写一个高效的算法在m x n 维矩阵中查找一个值,这个矩阵有以下特性:
矩阵的每一行的数是有序的。
每一行的第一个数比上一行的最后一个大。
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]]
Given target = 3
, return true
.
思路:
二分查找。
代码1:
class Solution {public: bool searchMatrix(vector<vector<int> > &matrix, int target) { int row = matrix.size(); if(row == 0) return false; int col = matrix[0].size(); for(int i = 0 ; i < row ; i++) { if(matrix[i][0] > target || matrix[i][col-1] < target) continue; int begin = 0 , end = col-1; while(begin <= end) { int mid = (begin + end)/2; if(matrix[i][mid] == target) return true; if(matrix[i][mid] > target ) end = mid - 1; else begin = mid + 1; } } return false; }};
代码2:
class Solution {public: bool searchMatrix(vector<vector<int> > &matrix, int target) { int row = matrix.size(); if(row == 0) return false; int col = matrix[0].size(); int begin = 0 ; int end = row * col - 1; while(begin <= end) { int mid = (begin + end)/2; if(target == matrix[mid/col][mid%col]) return true; if(target < matrix[mid/col][mid%col]) end = mid - 1; else begin = mid + 1; } return false; }};
0 0
- LeetCode OJ 之 Search a 2D Matrix (二维矩阵的搜索)
- LeetCode OJ 之 Search a 2D Matrix II (二维矩阵查找)
- 【LeetCode-面试算法经典-Java实现】【074-Search a 2D Matrix(搜索二维矩阵)】
- 第三周:240. Search a 2D Matrix II(搜索二维矩阵之二)
- LeetCode 74. Search a 2D Matrix(搜索矩阵)
- leetcode解题之 Search a 2D Matrix java 版(在二维矩阵中查找)
- LintCode Search a 2D matrix 搜索二维矩阵
- leetCode 74.Search a 2D Matrix(搜索二维矩阵) 解题思路和方法
- 图解 leetCode 74.Search a 2D Matrix(搜索二维矩阵)
- Leetcode Search a 2D Matrix 搜索二维表
- 28.Search a 2D Matrix-搜索二维矩阵(容易题)
- 38.Search a 2D Matrix II-搜索二维矩阵 II(中等题)
- Search a 2D Matrix II(搜索一个二维矩阵)
- 240. Search a 2D Matrix II(搜索二维矩阵)
- Search a 2D Matrix 特殊二维矩阵的查找
- LeetCode 74 Search a 2D Matrix(搜索2D矩阵)
- LeetCode | Search a 2D Matrix(二维矩阵中查找)
- LeetCode OJ:Search a 2D Matrix
- 【UNIX】内核对内核空间内存的管理以及对用户进程的堆内存分布
- NSDate比较
- IOS 开发学习一 基础知识
- POJ 3295-Tautology(构造法+栈)
- Sublime Text 3 快捷键汇总
- LeetCode OJ 之 Search a 2D Matrix (二维矩阵的搜索)
- 标准IO之格式化输入和输出
- UML画图—机房收费(一)
- tableView跳转界面时取消之前界面被选中状态
- 2014,2015
- 关于C和C++中void mian()和int main()的问题
- XML约束之DTD
- 【1295】螺旋方阵
- ubuntu(14.10) 配置ssh 服务