LeetCode 74. Search a 2D Matrix

题目描述

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;
    }
};
全部评论

相关推荐

26应届求职ing:你这是报了豆音四哥的班?双非本硕拿这两个项目写简历里投100多家嵌软也没什么面试,感觉项目简单了,很多人用
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务