LeetCode 74. Search a 2D Matrix
2016-09-04 15:45
363 查看
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 小,但是它后面紧邻的数比target 大。即要找最后一个比target小的数(如果存在的话)。根据二分查找的算法特性,它返回的值应该是跟target 最相邻的数:要么是target 本身,要么是最大的比它小的数,要么是最小的比它大的数。如一列数……3,7,10,20,35…… 要查找11的话,返回的会是10或者20,在第一层查找中返回20是不符合要求的,应该调整一下返回10。
优化。。。
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 小,但是它后面紧邻的数比target 大。即要找最后一个比target小的数(如果存在的话)。根据二分查找的算法特性,它返回的值应该是跟target 最相邻的数:要么是target 本身,要么是最大的比它小的数,要么是最小的比它大的数。如一列数……3,7,10,20,35…… 要查找11的话,返回的会是10或者20,在第一层查找中返回20是不符合要求的,应该调整一下返回10。
class Solution { public: bool searchMatrix(vector<vector<int> >& matrix, int target) { int low=0,high=matrix.size()-1,mid; while(low<=high){ mid=(low+high)/2; if(matrix[mid][0]==target){ return true; } else if(matrix[mid][0]<target){ low=mid+1; }else if(matrix[mid][0]>target){ high=mid-1; } } if(matrix[mid][0]>target){ if(mid>0&&matrix[mid-1][0]<target){ mid-=1; } } vector<int> vec=matrix[mid]; low=0;high=vec.size()-1; while(low<=high){ mid=(low+high)/2; if(vec[mid]==target){ return true; } else if(vec[mid]<target){ low=mid+1; }else { high=mid-1; } } return false; } };
优化。。。
相关文章推荐
- 模式识别之聚类
- dd命令中seek和skip的用法
- URI URN URL
- java获取域名Whois注册信息
- (一)@Input属性讨论
- 四校联考 tree3
- Mysql-5.6.30卸载
- PHP 通用检测函数集
- 第4章 表达式
- var React = require(“react”)的require是啥?
- C#控制台基础 调用非静态类的静态方法与非静态方法
- 归并排序
- poj1717&&vijos p1222(背包变形)
- 切勿辜负青春一场
- 0904总结
- Jsoup爬取360电影网上的信息
- 倒计时
- 帮助理解js的小知识点:JavaScript添加样式
- 7_22_E题 Power of Matrix(矩阵快速幂+倍增)
- CSS3 background-size 属性