LeetCode | Search a 2D Matrix

来源:互联网 发布:transmac制作mac安装盘 编辑:程序博客网 时间:2024/06/06 18:03

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.

从一个二维数组里面寻找元素。
解决思路是从左下角开始寻找,因为数组的排列方式使得我们从左下角出发的话,比它大的位于右侧,比他小的位于上侧。
于是就可以利用这么一个递归的过程【事实上也可以写成非常简单的非递归】从而正确地找到该数字是否在这个矩阵里面。

class Solution {public:    bool searchMatrix(vector<vector<int>>& matrix, int target) {        int m=matrix.size();        int n=matrix[0].size();        return searchTarget(matrix,target,m-1,0);    }    bool searchTarget(vector<vector<int>>& matrix, int target,int x,int y) {        int m=matrix.size();        int n=matrix[0].size();        if(x<0 || x>=m || y<0 || y>=n) return false;        if(target==matrix[x][y]) return true;        if(target < matrix[x][y])        return searchTarget(matrix,target,x-1,y);        else        return searchTarget(matrix,target,x,y+1);    }};
0 0