Leetcode -- search a 2D matrix 2D ordered array query (AC)

Source: Internet
Author: User

Write an efficient algorithm that searches for a value inMXNMatrix. 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]

GivenTarget=3, ReturnTrue.

If binary search is directly performed on matrix elements, the time complexity is O (M * n). In fact, it is easy to find the corresponding row by searching, then, find the existence of the domain name in the row, and use the simplest direct lookup method. The time complexity is only O (m + n). If the two searches use binary lookup, the time complexity can be reduced to O (logm + logn). The following is the O (m + n) code:

 
Class solution {public: bool searchmatrix (vector <int> & matrix, int target) {If (matrix. empty () return false; int M = matrix. size (); int n = matrix [0]. size (); int I = 0, j = 0; while (I <M & target> = matrix [I] [0]) I ++; I --; if (I =-1) return false; while (j <n) {If (target = matrix [I] [J]) return true; else J ++ ;} return false ;}};



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.