LeetCode 之 Search a 2D Matrix
2016-04-11 13:01
309 查看
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:
Given target =
这个经过分析后会发现其实就是考察在有序数组中查找给定元素的题,使用二分查找进行了,需要注意到数组索引和2D矩阵索引的转换就行了,代码如下(递归和循环):
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.
这个经过分析后会发现其实就是考察在有序数组中查找给定元素的题,使用二分查找进行了,需要注意到数组索引和2D矩阵索引的转换就行了,代码如下(递归和循环):
class Solution { public: /* bool searchMatrix(vector<vector<int>>& matrix, int target) { if(!matrix.size()) return false; int row=matrix.size(); int col=matrix[0].size(); int num=row*col; return searchMatrix(matrix,target,0,num-1,row,col); } bool searchMatrix(vector<vector<int>>& matrix, int target,int low,int high,int row,int col){ if(matrix[low/col][low%col]>target) return false; if(matrix[high/col][high%col]<target) return false; //if(matrix[low/col][low%row]==target||matrix[high/col][high%row]==target) return true; if(low==high) return matrix[low/col][low%col]==target; int mid=(low+high)/2; if(matrix[mid/col][mid%col]>=target) return searchMatrix(matrix,target,low,mid,row,col); else if(matrix[mid/col][mid%col]<target) return searchMatrix(matrix,target,mid+1,high,row,col); }*/ bool searchMatrix(vector<vector<int>>& matrix, int target){ if(!matrix.size()) return false; int row=matrix.size(); int col=matrix[0].size(); int num=row*col; int low=0,high=num-1; while(low<high){ if(matrix[low/col][low%col]>target) return false; if(matrix[high/col][high%col]<target) return false; int mid=(low+high)/2; if(matrix[mid/col][mid%col]>=target){ high=mid; }else if(matrix[mid/col][mid%col]<target){ low=mid+1; } } return matrix[low/col][low%col]==target; } };
相关文章推荐
- 量化生产力Quantifying Productivity
- leetcode 108. Convert Sorted Array to Binary Search Tree
- 从CIFAR-10手工分类中学到的经验教训Lessons learned from manually classifying CIFAR-10
- 算法时间复杂度分析
- 不可重入函数总结
- C++第3次上机实验-个人所得税计算机
- 计算机视觉和人工智能的状态:我们已经走得很远了 The state of Computer Vision and AI: we are really, really far away.
- Android 环境变量
- JScrollPane自动乡下滚动
- block,inline和inline-block概念和区别
- 0、mac下安装mysql
- Scrapy设置之深入
- python的使用环境总结
- python的使用环境总结
- BroadcastReceiver
- jxl和POI的区别
- 量化Hacker News 中50天的数据 Quantifying Hacker News with 50 days of data
- poj-1276 Cash Machine(多重背包)
- VS2013常用快捷键
- 基于ZooKeeper的分布式Session实现