Leetcode刷题26-240.搜索二维矩阵 II(C++)

题目来源:链接: [https://leetcode-cn.com/problems/search-a-2d-matrix-ii/].

1.问题描述

编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:

每行的元素从左到右升序排列。
每列的元素从上到下升序排列。

示例1:

现有矩阵 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]
]
给定 target = 5,返回 true。
给定 target = 20,返回 false。

2.我的解决方案

首先想到的是暴力解决法(时间复杂度为大O的平方),但是题目的递增条件还没用到,下面来继续优化。。。
代码如下:

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        for(int i = 0; i < matrix.size(); ++i)
        {
            for(int j = 0; j < matrix[i].size(); ++j)
            {
                if( matrix[i][j] == target)
                {
                    return true;
                }
            }
        }
        return false;
    }
};

3.大神们的解决方案

大神就是大神呀。
巧妙的运用了 题目给出的 递增条件。。。

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if(matrix.size() == 0)
        {
            return false;
        }
        int i = 0;
        int j = matrix[0].size() - 1;
        while( i < matrix.size() && j >= 0)
        {
            if(matrix[i][j] == target)
            {
                return true;
            }
            else if(matrix[i][j] < target)
            {
                ++i;
            }
            else
            {
                --j;
            }
        }
        return false;
    }
};
//提速专用 谢谢。
static auto _____ = []() 
{
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();

4.我的收获

要勤学勤思考,练得多了,我相信就会有大神的思路了,哈哈哈

2019/3/17 胡云层 于南京 26

猜你喜欢

转载自blog.csdn.net/qq_40858438/article/details/88624889