欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 74. Search a 2D Matrix

程序员文章站 2022-07-14 17:57:09
...

题目描述

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.

思路

  1. 每一行从左到右递增
  2. 本行的第一个比上一行的最后一个大。

给你一个数看有没有在矩阵里。

利用右上角来比较,比右上角小,列数减一,比右下角大行数加一,这样一步一步靠近结果。

代码

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if (matrix.size() == 0)
            return false;
        if (matrix[0].size() == 0)
            return false;
        int row = matrix.size();//行数
        int collor = matrix[0].size();//列数
        int nowrow = 0, nowcollor = collor - 1;
        while (nowrow < row && nowcollor >= 0)
        {
            if (target > matrix[nowrow][nowcollor])//第一行最后一列
            {
                nowrow += 1;
            }
            else if (target < matrix[nowrow][nowcollor])
            {
                nowcollor -= 1;
            }
            else
            {
                return true;
            }
        }
        return false;
    }
};