• #Leetcode# 74. Search a 2D Matrix


    https://leetcode.com/problems/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.

    Example 1:

    Input:
    matrix = [
      [1,   3,  5,  7],
      [10, 11, 16, 20],
      [23, 30, 34, 50]
    ]
    target = 3
    Output: true
    

    Example 2:

    Input:
    matrix = [
      [1,   3,  5,  7],
      [10, 11, 16, 20],
      [23, 30, 34, 50]
    ]
    target = 13
    Output: false

    代码:

    class Solution {
    public:
        bool searchMatrix(vector<vector<int>>& matrix, int target) {
            if(matrix.empty() || matrix[0].empty()) return false;
            int n = matrix.size(), m = matrix[0].size();
            int row = 0, line = m - 1;
            while(1) {
                if(matrix[row][line] == target) return true;
                else if(matrix[row][line] > target) line --;
                else row ++;
    
                if(row >= n || line < 0) break;
            }
            return false;
        }
    };
    

      这个问题之前在去苏州的高铁上看书的时候看到过 因为是排序好的数组 所以每次去看右上的数字 如果比 $target$ 大的话列就向左移 否则行向下移 这样就不用 $O(m * n)$ 的方法去做了 这个应该就是 $O(m)$ 或者 $O(n)$ 的了  但是写的时候莫名其妙很鬼畜的 WA 不知道哪里写错就在 cb 里写好然后改一下格式提交 AC 还是很爱马虎啊 难受了

  • 相关阅读:
    Python 必备神器
    python 常用库
    Sublime Text3 配置 Python2 Python3
    Python JSON
    Sublime Text3 3143 注册码
    EFCode First 导航属性
    EF Code First:实体映射,数据迁移,重构(1)
    Entity Framework 复杂类型
    EF 7 Code First
    EF Code First 导航属性 与外键
  • 原文地址:https://www.cnblogs.com/zlrrrr/p/10012177.html
Copyright © 2020-2023  润新知