美文网首页
74.搜索二维矩阵

74.搜索二维矩阵

作者: HITZGD | 来源:发表于2018-11-19 16:22 被阅读0次

题目
编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:

每行中的整数从左到右按升序排列。
每行的第一个整数大于前一行的最后一个整数。

示例 1:
输入:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
输出: true

示例 2:
输入:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13

#include <vector>
using namespace std;
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        
        int rows = matrix.size(), cols = matrix[0].size();
        if (matrix.empty() || cols == 0) return false;
        for (int i = 0; i < rows; i++)
        {
            if (matrix[i][cols - 1] < target) continue;
            if (matrix[i][cols - 1] >= target && matrix[i][0] <= target)
            {
                for (int j = 0; j <= cols - 1; j++)
                {
                    if (matrix[i][j] == target) return true;
                }
                return false;
            }
        }
        
    }
};

int main(int argc, char* argv[])
{
    vector<vector<int>> test = { { 1,   3,  5,  7 }, { 10, 11, 16, 20 }, { 23, 30, 34, 50 } };
    vector<vector<int>> test2 = {{1}};
    auto res = Solution().searchMatrix(test2, 1);
    return 0;
}

输出: false

相关文章

网友评论

      本文标题:74.搜索二维矩阵

      本文链接:https://www.haomeiwen.com/subject/sbdafqtx.html