美文网首页程序员
Leetcode - Search a 2D Matrix

Leetcode - Search a 2D Matrix

作者: 哈比猪 | 来源:发表于2016-09-27 19:02 被阅读0次

题目链接

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.

For example,
Consider the following matrix:

图1-1 题目

Given target = 3, return true

解题思路

TODO (稍后补充)

解答代码

  • 第一种方法(会超时): 二分查找
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if (matrix.empty()) return false;
        int rowCnt = matrix.size();
        int colCnt = matrix[0].size();
        int numCnt = rowCnt * colCnt;
        int lineNo = rowCnt - 1;
        int colNo = colCnt - 1;
        
        while(lineNo >= 0 && colNo >= 0) {
            if (matrix[lineNo][colNo] == target) return true;
            if (matrix[lineNo][colNo] > target) {
                int curNo = (lineNo+1)*(colNo+1);
                int nextNo = curNo / 2;
                lineNo = nextNo / (colCnt+1);
                colNo = nextNo % (colCnt+1);
            }
        }
        return false;       
        
    }
};

相关文章

网友评论

    本文标题:Leetcode - Search a 2D Matrix

    本文链接:https://www.haomeiwen.com/subject/gcxhyttx.html