ITPub博客

首页 > > > [LeetCode] Search a 2D Matrix

[LeetCode] Search a 2D Matrix

作者:Ruiyuan Li 时间:2015-06-23 00:00:00 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,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

Given target = 3, return true.

解题思路:

题意为给定一个矩阵和一个目标值,判断目标值是否在矩阵中存在。矩阵满足:每一行从左往右递增,后一行的第一个元素大于前一行最后一个元素。

可以考虑二分查找法,将一维坐标转化成二维坐标即可。

class Solution {
public:
    bool searchMatrix(vector>& matrix, int target) {
        //二分查找,将矩阵查找转化成线性查找
        int m = matrix.size();
        if(m==0){
            return false;
        }
        int n = matrix[0].size();
        if(n==0){
            return false;
        }
        int start = 0, end = m*n-1;
        while(start<=end){
            int middle = (start + end)/2;
            int x = middle / n;
            int y = middle % n;
            if(matrix[x][y]==target){
                return true;
            }else if(matrix[x][y]


转载请注明: » [LeetCode] Search a 2D Matrix
<!-- -->

原文作者:;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2020-05-21

  • 博文量
    495
  • 访问量
    4825