[Leetcode] (python): 074-search a 2D Matrix

Source: Internet
Author: User

Source of the topic

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

Write an efficient algorithm, searches for a value in a m x n Matrix. This matrix has the following properties:

    • Integers in each row is sorted from the left to the right.
    • The first integer of each row was greater than the last integer of the previous row.

Test instructions Analysis

Input:a Matrix and a target to query

Output:true or False

Conditions: Find an element in a matrix, notice that the matrix is ordered

Topic ideas

Find out which column to locate in column two, and then double-click the boundary condition.

PS: In fact, directly in the column search, found low-1 less than 0 o'clock, directly return false can be, but the paste code can be ported to the insertion element of the binary ordering inside, in order to unify there is no change.

AC Code (PYTHON)

1 __author__='YE'2 3 classsolution (object):4     defSearchmatrix (self, Matrix, target):5         """6 : Type Matrix:list[list[int]]7 : Type Target:int8 : Rtype:bool9         """Tenm =len (Matrix) Onen =Len (matrix[0]) ALow =0 -High = M-1 -  the          whileLow <=High : -Mid = (low + high)/2 -             ifMatrix[mid][0] = =Target: -                 returnTrue +             elifMatrix[mid][0] >Target: -High = Mid-1 +             Else: ALow = mid + 1 atrow = Low-1 -         ifRow <0: -row =0 -  -Low =0 -High = N-1 in  -          whileLow <=High : toMid = (low + high)/2 +             ifMatrix[row][mid] = =Target: -                 returnTrue the             elifMatrix[row][mid] >Target: *High = Mid-1 $             Else:Panax NotoginsengLow = mid + 1 -         returnFalse the  +Matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,50]] Atarget = 16 the Print(Solution (). Searchmatrix (Matrix,target))

[Leetcode] (python): 074-search a 2D Matrix

Related Article

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.