12ms C++ solution


  • 1
    S

    Start from upper-right corner.
    If target is less than current element move left.
    else move down.

    class Solution {
    public:
        bool searchMatrix(vector<vector<int>>& matrix, int target) {
            
            int m = matrix.size();
            if(m == 0) return false;
            
            int n = matrix[0].size();
            int r = 0, c = n-1;
            
            while(r < m && c >= 0) {
                
                if(target == matrix[r][c]) {
                    //cout << "r = " << r << "\t c = " << c << endl;
                    return true;
                }
                else{
                    if(target < matrix[r][c]){
                        c--;
                    }
                    else if(target > matrix[r][c]){
                        r++;
                    }
                }
            }
            return false;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.