74. Search a 2D Matrix
来源:互联网 发布:java猜数字游戏1~100 编辑:程序博客网 时间:2024/06/03 04:03
题目
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.
思路
本题矩阵的各种限制条件就是说明这个矩阵是有序的,查找target就是用二分法:
class Solution {public: bool searchMatrix(vector<vector<int>>& matrix, int target) { if(matrix.empty()) return false; int m=matrix.size(),n=matrix[0].size(); int first =0,end =m*n-1,mid = (m*n-1) / 2 ; while(first<=end) { if(target>matrix[m-1][n-1]||target<matrix[0][0]) return false; else if(target>matrix[mid/n][mid-(mid/n)*n]) { first = mid+1; mid = (first+end) /2; } else if(target<matrix[mid/n][mid-(mid/n)*n]) { end = mid - 1; mid = (first+end) /2; } else if(target==matrix[mid/n][mid-(mid/n)*n]) return true; } 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
- Kafka入门经典教程
- Android studio XListView 插件应用
- Oracle中rank() over, dense_rank(), row_number() 的区别
- SpringMVC传参,接参,集中传参,jsp页面提参的方式,以及关于SpringMVC下载和异常方式
- SVN服务器搭建和使用(三)
- 74. Search a 2D Matrix
- Linux常用命令
- hbase表空间(namespace)
- Java序列化的几种方式以及序列化的作用
- Java内部类详解
- 牛客网刷题总结1
- jQuery:基础学习(2)属性,CSS,文档,元素筛选
- JMS(三):DeliveryMode例子,JMSReplyTo,Selector
- 算法题/二叉树的镜像