Home > Database > Mysql Tutorial > Search a 2D Matrix

Search a 2D Matrix

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-07 15:32:54
Original
1171 people have browsed it

https://oj.leetcode.com/problems/search-a-2d-matrix/ 1、题目要求:在一个m×n的矩阵matrix里面查找目标target,如果查找成功返回true,否则返回false。 矩阵matrix的具有以下性质: 1)矩阵每行的元素从左到右递增排序; 2)每行的第一个元素比上一行的最

https://oj.leetcode.com/problems/search-a-2d-matrix/


1、题目要求:在一个m×n的矩阵matrix里面查找目标值target,如果查找成功返回true,否则返回false。

矩阵matrix的具有以下性质:

1)矩阵每行的元素从左到右递增排序;

2)每行的第一个元素比上一行的最后一个元素大;

例:假设个定矩阵如下,给定目标值target= 3, 则返回true.

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


2、解题思路:用每行的第一个元素进行二分查找,确定target所在行,然后在所在行进行二分查找;


class Solution {
public:
    bool searchMatrix(vector<vector> > &matrix, int target) {
        int n= matrix.size();
        int left= 0, right= n-1, mid;
        //首先找到target所在的行
        while(leftmatrix[mid][0])
                left= mid+1;
            else if(target<matrix right="mid-1;" else return true if false int row="left-1;" left="0," while mid="(left+right)/2;">matrix[row][mid])
                left= mid+1;
            else if(target<matrix right="mid-1;" else return true false><br>
<br>



</matrix></matrix></vector>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template