Wins the offer - to find a two-dimensional array - python

Title Description :

(The length of each one-dimensional array of same), each row from left to right in order of ascending sort, to sort each column in a two-dimensional array in order of increasing from top to bottom. A complete function, enter such a two-dimensional array and an integer, it is determined whether the array contains the integer.

Ideas :

  • Violence Solving Method : As the array elements are stored according to the law, for x i , j x_{i,j} It has x i 1 , j < x i , j < x i + 1 , j x_{i-1,j}<x_{i,j}<x_{i+1,j} with x x , j 1 < x i , j < x x , j + 1 x_{x,j-1}<x_{i,j}<x_{x,j+1} . So, when a lower dimensional array of a violent way is if there is one at the integer comparison to find the array.
  • Clever method : Due to the existence of a law, the position where we can from the smallest element position or the largest of the element, that is the bottom left or top right corner of the two-dimensional array to start looking. If the elements of the current position is less than the number of lookups, the number of rows plus 1; otherwise, the number of columns plus one.

    Here Insert Picture Description

AC Code

Violence Solving Method

# -*- coding:utf-8 -*-
class Solution:
    # array 二维列表
    def Find(self, target, array):
        data = array[0]
        # 全部元素
        for i in range(1, len(array)):
            data.extend(array[i])
        
        if target in data:
            return True
            
        return False

Clever method

# 下三角寻找
# -*- coding:utf-8 -*-
class Solution:
    # array 二维列表
    def Find(self, target, array):
        # write code here
        if array == None:
            return None
        # 行数和列数
        rows, cols = len(array), len(array[0])
        # 下三角寻找
        row = rows - 1
        col = 0
        while row >= 0 and col <= cols - 1:
            if array[row][col] == target:
                return True
            elif array[row][col] > target:
                row -= 1
            else:
                col += 1
        
        return False

# 上三角寻找
# -*- coding:utf-8 -*-
class Solution:
    def Find(self, target, array):
        # write code here
        if array == None:
            return None
            
        # 行数和列数
        rows, cols = len(array), len(array[0])
        col = cols - 1
        row = 0
        while col >= 0 and row <= rows - 1:
            if array[row][col] == target:
                return True
            elif array[row][col] > target:
                col -= 1
            else:
                row += 1
        
        return False
Published 289 original articles · won praise 103 · Views 200,000 +

Guess you like

Origin blog.csdn.net/Forlogen/article/details/104884269