Jianzhi offer brushing notes-find a two-dimensional array

Write a custom catalog title here

The idea I think is to compare the size of the target and the center value of the matrix. If the target is large, the 1/4 matrix in the upper left of the center is excluded, and if the target is small, the 1/4 matrix in the lower right is excluded. Then divide the remaining 3/4 matrix into three parts, recursively call the function to find the three matrices.
code show as below:

import numpy as np
class Solution:
    # array 二维列表
    def Find(self, target, array):
        # write code here
        print(array)
        array = np.array(array)
        if array.size == 0:
            return False
        col_r = array.shape[0]
        row_r = array.shape[1]
        col_m = int((col_r-1)/2)
        row_m = int((row_r-1)/2)
        anchor = array[col_m, row_m]
        if target < anchor:
            return self.Find(target, array[:col_m,:row_m]) or\
             self.Find(target, array[col_m:col_r,:row_m]) or\
              self.Find(target, array[:col_m,row_m:row_r])
        elif target > anchor:
            return self.Find(target, array[col_m+1:col_r,row_m+1:row_r]) or\
             self.Find(target, array[col_m+1:col_r,:row_m+1]) or\
              self.Find(target, array[:col_m+1,row_m+1:row_r])
        else:
            return True

However, the test speed is very low, because it is the complexity of log(4/3, m n). When the matrix is ​​larger than 4, the speed will be slower than O(m+n). So use binary search to search from the upper right corner, the code is as follows:

class Solution(object):
    def findNumberIn2DArray(self, matrix, target):
        if len(matrix) == 0:
            return False
        r = len(matrix[0])-1
        t = 0
        max_c = len(matrix)
        while r >= 0 and t < max_c:
            anchor = matrix[t][r]
            if target == anchor:
                return True
            elif target > anchor:
                t+=1
            else:
                r-=1
        return False

This question is still relatively simple, that is, the code is not skilled enough, pay attention to the judgment of the empty input matrix

Guess you like

Origin blog.csdn.net/baidu_37360677/article/details/108556287