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.


算法一,

1. 選擇左下角的元素

2,如果該值大於target,則可以確定,在當前行中,不存在target。從而可以排除掉一行。

3,如果該值小於target,則可以確定,在當前列中,不存在target。從而可以排除掉一列。

4,對剩餘矩陣,重複步驟2,3. 直到找到,或者剩餘矩陣爲空。

執行過程,就是不斷的排除下面的行,或者左邊的列。

由於每次循環都排除掉一行或者一列,故算法時間複雜度爲O(m+n)。


另外,除了選擇左下角,也可以選擇右上角。


在leetcode上實際執行時間爲260ms。

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



算法二, 折半。

選取矩陣的中心點,與target作比較。

1. 如果該值小於target,則可以排除掉左上角4分之1矩陣。繼續在剩餘4分之3矩陣中查找。

2. 如果該值大於target,則可以排除掉右上角4分之1矩陣。


在leetcode上實際執行時間爲556ms。

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if (matrix.empty() || matrix[0].empty())
            return false;
        return searchMatrix(matrix, 0, 0, matrix.size()-1, matrix[0].size()-1, target);
    }
    
    bool searchMatrix(vector<vector<int>>& matrix, int x1, int y1, int x2, int y2, int target) {
        if (x1 > x2 || y1 > y2)
            return false;
        
        const int x = x1 + (x2 - x1) / 2;
        const int y = y1 + (y2 - y1) / 2;
        if (matrix[x][y] == target)
            return true;
        else if (matrix[x][y] > target)
            return searchMatrix(matrix, x1, y1, x-1, y2, target) || searchMatrix(matrix, x, y1, x2, y-1, target);
        else
            return searchMatrix(matrix, x1, y+1, x2, y2, target) || searchMatrix(matrix, x+1, y1, x2, y, target);
    }
};



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章