Leetcode 2D Matrix (search 2D matrices)

Source: Internet
Author: User

translation
写一个高效算法用于在一个m x n的矩阵中查找一个值。这个矩阵有如下属性:每行的整型数都是从左到右排序的。每行的第一个元素都比上一行的最后一列大。例如,考虑如下矩阵:[  [1,   3,  5,  7],  [10111620],  [233034503,返回true。
Original
Write an efficient algorithm thatSearches forA valueinchAn M x n matrix. This matrix has theFollowing properties:integersinchEach row is sorted fromLeft toRight. The First integer  ofEach row is Greater than  the  Last integer  of  thePrevious row. For Example,consider theFollowing matrix:[[1,3,5,7],  [Ten, One, -, -],  [ at, -, the, -]]given target =3,return true.
Analysis

Maybe because I'm sleepy, so both the algorithm and myself, are inefficient ...

The following code is also a change ...

BOOLSearchmatrix ( vector<vector<int>>& Matrix,intTarget) {if(matrix[0][0] > Target)return false; for(inti =0; I < matrix.size (); ) { for(intj =0; J < Matrix[i].size (); ) {if(i = = Matrix.size ()-1&& Matrix[i][j] < target) {if(J >= Matrix[i].size ())return false; J + =1;if(Matrix[i][j] > target)return false; }Else if(Matrix[i][j] < target && matrix[i+1][J] > Target) {j + =1;if(J >= Matrix[i].size ())return false;if(Matrix[i][j] > target)return false; }Else if(Matrix[i][j] < target && Matrix[i +1][J] <= target) {i + =1; }Else if(Matrix[i][j] = = target) {return true; }if(i = = Matrix.size ()-1&& J = = Matrix[i].size ()) {return false; }        }    }return false;}

Let's do it again tomorrow and do it again.

Leetcode 2D Matrix (search 2D matrices)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.