Jianzhi offer04: Find a number in an ordered two-dimensional array


1. Topic description

insert image description here

2. Problem-solving ideas and code implementation

1. Problem-solving ideas

Method 1:
Violent traversal, you can do pruning operation, if the number of traversal is greater than target, just break directly.

Method 2:
Binary search, do a binary search for each line, python has a built-in function bisect, which is very convenient.

Method 3:
Search from the upper right corner to the lower left direction. If it is greater than the target, move one bit to the left. If it is smaller than the target, move one bit down.
This search method is applicable to ordered arrays. To start, you can also start from the lower left corner, like flowing water, slowly flowing in a direction just larger than the target.

2. Code implementation

Method 3 code is as follows (example):

class Solution:
    def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
        # 从矩阵右上角开始,如果大于,就往左走,如果小于,就往下走
        n, m = len(matrix), len(matrix) and len(matrix[0])
        i, j = 0, m
        while i<n and j:
            if matrix[i][j-1]==target:
                return True
            elif matrix[i][j-1] > target:
                j-=1
            else:
                i+=1
        return False

Guess you like

Origin blog.csdn.net/weixin_45271005/article/details/131718018