Description:
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
.
解题思路:
方法一:
最普通的二维数组用两层循环遍历的方法。但是复杂度有O(m*n),非常高,代码如下:
class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { //int flag = 0; if(matrix.empty()||matrix[0].empty()) return false; int m = matrix.size(); int n = matrix[0].size(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (matrix[i][j] == target) { return true; } } } return false; } };
方法二:
从右上角开始遍历,根据这个二维数组的特殊排列性质,可以通过大小比较,选择向左或者向下,复杂度有所减少,为O(m),代码如下:
class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { if(matrix.empty()||matrix[0].empty()) return false; int m = matrix.size(); int n = matrix[0].size(); int i = 0; int j = n-1; while(i<=m-1 && j>=0) { if (matrix[i][j] == target) { return true; } else if (matrix[i][j] > target) { j--; } else { i++; } } return false; } };