Leetcode - Search a 2D Matrix

题目链接

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;       
        
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,360评论 0 33
  • I use measuring instrument for lofting.I feel excited for...
    全心全意为自己而活阅读 1,526评论 0 0
  • 此一刻 最无助的时候 帮不上的时候 给不了的时候 不知道怎么办的时候 六神无主的时候 心空空荡荡的时候 我不知道在...
    小草_d5ad阅读 2,571评论 10 22
  • (1)、答应的事情一定要做到,经验自己的信誉。经营自己的事业,我的事业完全在自己的掌握当中!!!一切都在自己的掌握...
    蛮将阅读 1,355评论 0 1
  • 每个孩子都有自己的成长规律。这一生里面有三个重要的转折时期。作为父母必须要尊重孩子这三个成长时期。如果父母硬要去按...
    心如莲花_fea1阅读 4,268评论 6 6

友情链接更多精彩内容