LeetCode 74 / 240. Search a 2D Matrix I+II

2d appears to be a problem, but in fact can still use half of one-dimensional thinking to do, nothing more than just calculate the horizontal and vertical coordinates.

The following open interval with the writing, writing is okay the closed interval.

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int m=matrix.size(), n=m==0?0:matrix[0].size();
        if (m==0 || n==0) return false;
        
        int low=0, high=m*n;
        while (low<high){
            int mid=(low+high)/2;
            int cur=matrix[mid/n][mid%n];
            if (cur==target) return true;
            else if (cur<target) low=mid+1;
            else high=mid;
        }
        return false;
    }
};

The time complexity of O (log (mn))

 

240. Search a 2D Matrix II

If two points followed ideas, only the first half of the longitudinal, transverse direction two. If not found, continue in both directions half.

The time complexity of O (log (n!)), Because the worst case to be done n times two.

Binary Search Tree Model

The lower left corner of similar elements as the root of BST. As long as we move the relationship between the current element and target according to find the target.

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

The time complexity of O (m + n)

Divide and Conquer

To be continued ...

Guess you like

Origin www.cnblogs.com/hankunyan/p/11582393.html