240. Search a 2D Matrix II

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 i = 0, j = n - 1;
    while (i < m && j >= 0) {
        if (matrix[i][j] == target)
            return true;
        else if (matrix[i][j] > target) {
            j--;
        } else 
            i++;
    }
    return false;
}
};

/*Time Limit Exceeded*/
/*
class Solution {
private:
class Tuple {
public:
int val;
int row;
int col;
public:
Tuple(int r, int c, int v) :val(v), row(r), col(c) {};
bool operator<(const Tuple& e2) const {
return this->val > e2.val;
};
};
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
auto my_compare = [](const Tuple& e1, const Tuple& e2) {
return e1.val > e2.val;};
priority_queue<Tuple, vector<Tuple>, decltype(my_compare)> pq(my_compare);
if (0 == matrix.size()) return false;
int m = matrix.size();
int n = matrix[0].size();
if (0 == n) return false;
int row = -1;
for (int i = 0; i< m;i++) {
if (matrix[i][n - 1] >= target) { row = i; break; };
}
if (row == -1) return false;
for (int j = 0;j<n;j++) {
Tuple t1(row, j, matrix[row][j]);
pq.push(t1);
}
while (!pq.empty())
{
Tuple t = pq.top();
if (target < t.val) return false;
if (target == t.val) return true;


pq.pop();
if(t.row + 1 <=m-1)
pq.push(Tuple(t.row+1, t.col, matrix[t.row+1][t.col]));
}


return false;
}
};
*/
/*Time Limit Exceeded*/
/*
class Solution {
private:
class Tuple {
public:
int val;
int row;
int col;
public:
Tuple(int r, int c, int v) :val(v), row(r), col(c) {};
bool operator<(const Tuple& e2) const {
return this->val > e2.val;
};
};
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
auto my_compare = [](const Tuple& e1, const Tuple& e2) {
return e1.val > e2.val;};
priority_queue<Tuple, vector<Tuple>, decltype(my_compare)> pq(my_compare);
if (0 == matrix.size()) return false;
int m = matrix.size();
int n = matrix[0].size();
if (0 == n) return false;
int row = -1;
for (int i = 0; i< m;i++) {
if (matrix[i][n - 1] >= target) { row = i; break; };
}
if (row == -1) return false;
        int col =-1;
        for(int j = 0; j<n;j++){
            if (matrix[m-1][j] >= target) { col = j; break; };
        }
for (int j = col;j<n;j++) {
Tuple t1(row, j, matrix[row][j]);
pq.push(t1);
}
while (!pq.empty())
{
Tuple t = pq.top();
if (target < t.val) return false;
if (target == t.val) return true;


pq.pop();
if(t.row + 1 <=m-1)
pq.push(Tuple(t.row+1, t.col, matrix[t.row+1][t.col]));
}


return false;
}
};
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值