Search a 2D Matrix II(leetcode)

来源:互联网 发布:神仙道懒娃 源码 编辑:程序博客网 时间:2024/06/07 06:53

Search a 2D Matrix II

  • Search a 2D Matrix II
    • 题目
    • 解决
      • 规律解决


题目

leetcode题目
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 in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
For example,

Consider the following 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]
]

Given target = 5, return true.
Given target = 20, return false.

解析:我们需要解决的是知道给定的二维数组array和目标数target,判断target是否在array里面。而且给定的array中数与数之间是存在这样的规律——array[i][j] < array[i][j+1]array[i][j] < array[i+1][j],因此我们可以根据这个规律解决问题。


解决

规律解决

规律:array[i][j] < array[i][j+1]array[i][j] < array[i+1][j]
我们可以每次将target同array[i][column](column是array的列数)进行比较,判断target是否在array的这一行或者上一行。
复杂度为O(row+column)。

class Solution {public:    bool searchMatrix(vector<vector<int>>& matrix, int target) {        int row = matrix.size();        if (row == 0) {            return false; // 数组为空时,自然返回false        }        int column = matrix[0].size();        int i = 0; // 从第一行可是扫描数组        int j = column - 1;        while (i < row && j >= 0) {            if (matrix[i][j] == target) {                return true;            } else if (matrix[i][j] < target) {                i++; // target可能在下一行            } else {                j--; // target可能在这一行            }        }        return false;    }};

leetcode结果:129 / 129 test cases passed. Runtime: 66 ms