LeetCode 240. Search a 2D Matrix II

題目

O(m+n)

class Solution {
public:
    int n,m;
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        
        n = matrix.size();
        if(n==0)
            return false;
        m = matrix[0].size();
        if(m==0)
            return false;
        
        int i=0;
        int j=m-1;
        
        while(true)
        {
            if(i<0||i>=n||j<0||j>=m)
                break;
            
            if(matrix[i][j]==target)
                return true;
            else if(matrix[i][j]<target)
                i++;
            else
                j--;
        }
        
        return false;
        
    }
    
  
   
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章