siddontang
LeetCode题解

Updated 2 months ago

hitzhangjie (@hitzhangjie) started discussion #39

4 months ago · 0 comments

Open

search a 2D matrix, algorithm can be optimized for better performance?

class Solution {
public:
    bool searchMatrix(vector<vector<int> > &matrix, int target) {
        /* we set the corner case as below:
           1, if the row number of input matrix is 0, we set it false
           2, if the colomun number of input matrix is 0, we set it false*/
        if(matrix.size() == 0)
            return false;
        if(matrix[0].size() == 0)
            return false;
        int rowNumber = 0;
        int colNumber = matrix[0].size()-1;
        while(rowNumber < matrix.size() && colNumber >= 0)
        {
            if(target < matrix[rowNumber][colNumber])
                --colNumber;
            // for example, matrix[0] = [ 1 3 6 7 ], target = 5,
            // ++ rowNumber can be optimized by adding jugdge statement
            else if(target > matrix[rowNumber][colNumber]) {
                if(colNumber == matrix[rowNumber].size()-1)
                    ++rowNumber;
                else
                    return false;
            }
            else
                return true;
        }
        return false;
    }
};

No comments on this discussion.


to join this conversation on GitBook. Already have an account? Sign in to comment
Notifications

You’re not receiving notifications from this thread.


1 participant