Search a 2D Matrix II_Week2

来源:互联网 发布:c语言函数的定义与调用 编辑:程序博客网 时间:2024/06/06 06:34

Search a 2D Matrix II_Week2

题目:(Search a 2D Matrix II) ←链接戳这里

题目说明:
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 in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
For example,

Consider the following matrix:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]

Given target = 5, return true.

Given target = 20, return false.

难度: Medium

解题思路:
1.由题可知,该矩阵每一行从左到右、每一列从上到下都是递增序列,所以很容易从其中的某个元素开始判断若该target存在则存才的区域,类似于平面的二分法。

2.取第一行的最后一个元素,即该行最大、该列最小的元素,若target比元素大,则可以检测下一行、若target比元素小,则可以往回检测该行、直到搜索出了该矩阵范围,若未寻到则是不存在。

代码如下:

#include <iostream>#include <vector>using namespace std;class Solution {public:    bool searchMatrix(vector<vector<int> >& matrix, int target) {        /*m,n 分别为矩阵的行数和列数*/        int m = matrix.size();        if (m < 1) {            return false;        }        int n = matrix[0].size();        int i = 0, j = n - 1;        /*从每行最后一个元素开始比较,大则往下,小则往左*/        while(i < m && j >= 0) {            if (matrix[i][j] > target) {                j--;            } else if (matrix[i][j] < target) {                i++;            } else {                return true;            }        }         return false;    }};
原创粉丝点击