Leetcode Search a 2D Matrix

Source: Internet
Author: User

Search a 2D matrix original problem of leetcode problem solving

In a matrix where each row is incremented from left to right, and the first number in the next row is larger than the last digit in the previous row, the target number is determined to exist.

Note the point:

    • No

Example:

Input:

matrix = [  [1,   3,  5,  7],  [10, 11, 16, 20],  [23, 30, 34, 50]]target = 3

Output: True

Thinking of solving problems

The matrix from left to right, from top to bottom, is an incremented array, which can be found by binary search. Now just find the array subscript to the matrix mapping relationship can be: i -> [i // n][i % n] , where I is the subscript in the array, n is the width of the matrix.

AC Source
 class solution(object):     def Searchmatrix(self, Matrix, target):        "" : Type Matrix:list[list[int]]: type Target:int:rtype:bool "" "m = len (matrix) n = Len (matrix[0]) L, h =0, M * N-1         whileL <= h:mid = l + (h-l)//2            ifMatrix[mid//n][mid% n] = = target:return True            elifMatrix[mid//n][mid% n] < Target:l = mid +1            Else: H = mid-1        return Falseif__name__ = ="__main__":assertSolution (). Searchmatrix ([[1,2,3], [4,5,6], [7,8,9]],5) ==True    assertSolution (). Searchmatrix ([[1,2], [3,4]],4) ==True    assertSolution (). Searchmatrix ([[1]],2) ==False

Welcome to my GitHub (Https://github.com/gavinfish/LeetCode-Python) to get the relevant source code.

Leetcode Search a 2D Matrix

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.