leetcode #74 in cpp
来源:互联网 发布:javascript iframe src 编辑:程序博客网 时间:2024/06/05 06:24
Solution:
We could perform 2 binary searches. The first search is to locate the specific row which potentially contains the target. Once we find the row, we perform binary search in the row to find the target.
Code:
class Solution {public: bool searchMatrix(vector<vector<int>>& matrix, int target) { int m = matrix.size(); int n = matrix[0].size(); if(target < matrix[0][0] || target > matrix[m-1][n-1]) return false; <span style="white-space:pre"></span>int lower_row = 0; int upper_row = m-1; int mid_row; //search for the specific row. The row we are looking for has a range that the target could fall in. //That is, the target should be larger than the first number and smaller than the last number in the row. while(lower_row <= upper_row){ mid_row = (lower_row + upper_row) / 2; if(matrix[mid_row][0] <= target && matrix[mid_row][n-1] >= target){ break; } if(matrix[mid_row][n-1] < target ){ lower_row = mid_row + 1; } else{ upper_row = mid_row - 1; } } if(lower_row > upper_row) return false;//if lower_row > upper_row, this means the specific row is not found, and thus there are no rows with range the target could fall in. We can termiante now. int lower_col = 0; int upper_col = n - 1; int mid_col; //binary search through the columns in the row while(lower_col <= upper_col){ mid_col = (lower_col + upper_col) /2; if(matrix[mid_row][mid_col] == target) return true; if(matrix[mid_row][mid_col] < target){ lower_col = mid_col + 1; }else{ upper_col = mid_col - 1; } } return false; }};
0 0
- leetcode #74 in cpp
- leetcode #12 in cpp
- Leetcode #13 in cpp
- Leetcode #14 in cpp
- leetcode %15 in cpp
- leetcode #16 in cpp
- leetcode #17 in cpp
- leetcode #18 in cpp
- leetcode #20 in cpp
- leetcode #21 in cpp
- leetcode #22 in cpp
- leetcode #23 in cpp
- leetcode #24 in cpp
- leetcode #25 in cpp
- leetcode #26 in cpp
- leetcode #27 in cpp
- leetcode #28 in cpp
- leetcode #29 in cpp
- CSS盒子模型各属性层级及基础知识
- OpenCV Python 直方图
- Ajax XMLHttpRequest对象的三个属性以及open和send方法
- iOS开发之runloop
- 判断两个View是否相同
- leetcode #74 in cpp
- 浅谈JAVA垃圾回收机制及其回收时机
- PyQt5:PyQt5中的菜单和工具栏、主窗口(7)
- 将1~6这6个数字按每行3个进行输出,输出时要求左边的数字比右边的大,上边的数字比下边的大,求出所有可能的填写方法并统计输出排列方法有多少种。
- oracle 简单查询
- PyQt5:菜单栏(8)
- 三. Ubuntu下安装SSH服务并配置securtCRT
- 网络设备中使用的算法
- SQL 分组排序group by