9.对有序矩阵进行搜索

1.问题陈述

2.问题分析

考虑到矩阵为有序矩阵呢个,下面的大于上面的,左面的小于右面的,所以可以从右上角进行搜索。

3.代码

bool searchMatrix(vector<vector<int> > &matrix, int target) 
    {
        int m=matrix.size();
        int n=matrix[0].size();
        int i=0,j=n-1;
        while(i < m && j > -1)
        {
            int cur =matrix[i][j];
            if(target==cur) return true;//如果检索到就终止
            else if(target>cur) {i+=1;}//没有检索的话小于当前值就向左移动,否则向下
            else{j-=1;}
        }
        return false;
        
    }

猜你喜欢

转载自blog.csdn.net/feng__shuai/article/details/81279329
今日推荐