leetcode240.搜索二维矩阵II

1.从右上角开始搜索,如果小于target则该行所有元素都不满足,行++。如果大于target,则该列所有元素都不满足。列–
参考:https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/66142/C%2B%2B-with-O(m%2Bn)-complexity

bool searchMatrix(vector<vector<int>>& matrix, int target) {
    int m = matrix.size(); //行
    if (m == 0) return false;
    int n = matrix[0].size(); //列

    int i = 0, j = n - 1; //从右上角开始搜索
    while (i < m && j >= 0) {
        if (matrix[i][j] == target)
            return true;
        else if (matrix[i][j] > target) {大于target,--
            j--;
        } else 
            i++; //小于target,行++
    }
    return false;
}

2.二分搜索
参考:
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/66235/2-clean-C%2B%2B-implementation-with-detailed-complexity-analysis

class Solution {
    public:
        bool searchMatrix(vector<vector<int>>& matrix, int target) {
            if(matrix.size()==0) return false;
            int row=matrix.size(), col=matrix[0].size();
            return help(matrix, 0, row-1, 0, col-1, target); //搜索子矩阵
        }
        
        bool help(vector<vector<int>>& matrix, int row_start, int row_end, int col_start, int col_end, int target) {
            if(row_start>row_end || col_start>col_end)  return false;
            int row_mid=(row_start+row_end)/2, col_mid=(col_start+col_end)/2; //找矩阵中间元素
            if(matrix[row_mid][col_mid]==target)    return true;
            else if(matrix[row_mid][col_mid]>target){ //如果大于target,则右下所有元素都不行,从左上,右上和左下去找
                /*** left-up || left-down || right-up ***/
                return help(matrix, row_start, row_mid-1, col_start, col_mid-1, target) ||
                    help(matrix, row_mid, row_end, col_start, col_mid-1, target) ||
                    help(matrix, row_start, row_mid-1, col_mid, col_end, target);
            }
            else{
                /*** right-down || left-down || right-up ***/
                return help(matrix, row_mid+1, row_end, col_mid+1, col_end, target) ||
                    help(matrix, row_mid+1, row_end, col_start, col_mid, target) ||
                    help(matrix, row_start, row_mid, col_mid+1, col_end, target);
            }
        }
    };

你可能感兴趣的:(leetcode)