关闭

leetcode #74 in cpp

标签: cppleetcode
57人阅读 评论(0) 收藏 举报
分类:

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

猜你在找
【直播】机器学习&数据挖掘7周实训--韦玮
【套餐】系统集成项目管理工程师顺利通关--徐朋
【直播】3小时掌握Docker最佳实战-徐西宁
【套餐】机器学习系列套餐(算法+实战)--唐宇迪
【直播】计算机视觉原理及实战--屈教授
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
【直播】机器学习之矩阵--黄博士
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
【直播】机器学习之凸优化--马博士
【套餐】Javascript 设计模式实战--曾亮
查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:6725次
    • 积分:1393
    • 等级:
    • 排名:千里之外
    • 原创:139篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档