74. Search a 2D Matrix

Problem: https://leetcode.com/problems/search-a-2d-matrix/

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row

Thought:

  search last row , last column and the left matrix (I didn't consider the second property)

  If I consider the second property, search for row then search the row would be much better.(O(log(mn)))

Code C++:

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if (matrix.size() < 1) {
            return false;
        }
        
        int m = matrix.size(), n = matrix[0].size();
        
        if (target > matrix[m - 1][n - 1]) {
            return false;
        } else if (target == matrix[m - 1][n - 1]) {
            return true;
        }
        
        if (m == 1) {
            return binary_search(matrix[0].begin(), matrix[0].end(), target);
        }
        if (n == 1) {
            vector<int> column;
            for (int i = 0; i < matrix.size(); i++) {
                column.push_back(matrix[i][0]);
            }
            return binary_search(column.begin(), column.end(), target);
        }
        
        vector<vector<int>> corner;
        vector<int> row;
        vector<int> column;
        
        for (int i = 0; i < m - 1; i++) {
            vector<int> temp;
            for (int j = 0; j < n - 1; j++) {
                temp.push_back(matrix[i][j]);
            }
            corner.push_back(temp);
        }
        
        for (int i = 0; i < n - 1; i++) {
            row.push_back(matrix[m - 1][i]);
        }
        
        for (int i = 0; i < m - 1; i++) {
            column.push_back(matrix[i][n - 1]);
        }
        
        return binary_search(row.begin(), row.end(), target) || binary_search(column.begin(), column.end(), target) || searchMatrix(corner, target);
    }
};

 

转载于:https://www.cnblogs.com/gavinxing/p/5715376.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值