#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 还是很爱马虎啊 难受了

posted @ 2018-11-24 15:00  丧心病狂工科女  阅读(159)  评论(0编辑  收藏  举报