[Leetcode]_74 Search a 2D Matrix

/**
 *  Index: 74
 *  Title: Search a 2D Matrix
 *  Author: ltree98
 **/

題意

在m*n的矩陣中尋找是否存在某個數。

  • 每行整數都是由小到大排序的
  • 每行第一個數都大於上一行最後一個數

我的

思路

順序查找

每次先與每行最後一個數比較,直到目標值小於最後數,則該數肯定在此行;再從該行從頭比較。

時間複雜度:O(m+n)
空間複雜度:O(1)

二分

這個矩陣兩個順序條件一列,明顯就是有序數組,可以用二分來進行解決。

要注意中間值對應的行列值關係。

時間複雜度:O(log(m*n))

空間複雜度:O(1)

實現

順序查找

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

二分查找

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

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