首页 > 学院 > 开发设计 > 正文

LeetCode 74. Search a 2D Matrix

2019-11-08 01:36:06
字体:
来源:转载
供稿:网友

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.

For example,

Consider the following matrix:

[  [1,   3,  5,  7],  [10, 11, 16, 20],  [23, 30, 34, 50]]

Given target = 3, return true.

answer:

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();        if(n == 0) return false;        int mLeft = 0, mRight = m - 1, nLeft = 0, nRight = n - 1;        int mMid = 0, nMid = 0;        while(mLeft <= mRight){            mMid = (mLeft + mRight) / 2;            nMid = (nLeft + nRight) / 2;            if(matrix[mMid][nMid] > target){                if(matrix[mMid][0] > target) mRight = mMid - 1;                else if(matrix[mMid][0] < target) break;                else return true;            }            else if(matrix[mMid][nMid] < target){                if(matrix[mMid][n - 1] > target) break;                else if(matrix[mMid][n - 1] < target) mLeft = mMid + 1;                else return true;            }             else return true;        }        if(mLeft > mRight) return false;                while(nLeft <= nRight){            nMid = (nLeft + nRight) / 2;            if(matrix[mMid][nMid] < target) nLeft = nMid + 1;            else if(matrix[mMid][nMid] > target) nRight = nMid - 1;            else return true;        }        return false;    }};


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表