【Leetcode】240. Search a 2D Matrix II(思维)

柔光的暖阳◎ 2022-01-21 03:05 248阅读 0赞

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.

Example:

Consider the following matrix:

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

Given target = 5, return true.

Given target = 20, return false.

题目大意:

在一个二维数组中找出target。数组按照行列数组由大到小顺序排列。

解题思路:

如果当前(0,0)的数比tar小,我们需要从行的方面考虑从0到m-1,i++

当前的数比tar大,我们需要从列方面考虑从n-1到0,j—

  1. class Solution {
  2. public:
  3. bool searchMatrix(vector<vector<int>>& maps, int tar) {
  4. int m = maps.size();
  5. if(m==0) return false;
  6. int n = maps[0].size();
  7. if(n==0) return false;
  8. int i = 0, j = n - 1;
  9. while(i<m&&i>=0&&j<n&&j>=0){
  10. int num = maps[i][j];
  11. if(num == tar) return true;
  12. if(num < tar){
  13. i++;
  14. }
  15. if(num > tar){
  16. j--;
  17. }
  18. }
  19. return false;
  20. }
  21. };

发表评论

表情:
评论列表 (有 0 条评论,248人围观)

还没有评论,来说两句吧...

相关阅读