74. Search a 2D Matrix
来源:互联网 发布:js重新加载div 编辑:程序博客网 时间:2024/05/16 23:49
Difficulty: Medium
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
bool searchMatrix(int** matrix, int matrixRowSize, int matrixColSize, int target) { int low_row = 0, high_row = matrixRowSize-1, low_col = 0, high_col = matrixColSize-1; int mid_row, mid_col; while(low_row <= high_row) { mid_row = (low_row + high_row)/2; if(target >= matrix[mid_row][0] && target <= matrix[mid_row][matrixColSize-1]) { while(low_col <= high_col) { mid_col = (low_col+high_col)/2; if (target == matrix[mid_row][mid_col]) return true; else if (target < matrix[mid_row][mid_col]) { high_col = mid_col - 1; } else { low_col = mid_col + 1; } } return false; } else if(target > matrix[mid_row][matrixColSize-1]) { low_row = mid_row+1; } else { high_row = mid_row-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
- 与Web集成
- [TensorFlow] win10安装TensorFlow
- interface
- 蓝桥杯2017模拟赛本科组题目
- Python学习
- 74. Search a 2D Matrix
- PowerDesign 16.5.5.2 (4734) 汉化包
- css
- zookeeper学习笔记
- C++从虚函数表的底层来看虚函数调用问题
- Arcgis:Python
- python 爬虫 教程(2)
- 接口和抽象类的个人理解
- 边缘分布