Technology Sharing

Leetcode74. Searching a two-dimensional matrix

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Give you a satisfying the following two propertiesm x nInteger matrices:

  • The integers in each row are arranged in non-strictly increasing order from left to right.
  • The first integer in each row is greater than the last integer in the previous row.

Give you an integertarget,iftargetIn the matrix, returntrue; Otherwise, returnfalse 。

hint:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 100
  • -104 <= matrix[i][j], target <= 104

Idea: First find the possible row, if it is in the row, then return true

  1. class Solution(object):
  2. def searchMatrix(self, matrix, target):
  3. """
  4. :type matrix: List[List[int]]
  5. :type target: int
  6. :rtype: bool
  7. """
  8. # 思路:先查找可能所在的行,如果在行里边,那么就返回true
  9. m = len(matrix)
  10. n = len(matrix[0])
  11. for i in range(m):
  12. if target in matrix[i]: # 如果在这一行中
  13. return True
  14. if target > matrix[i][n-1]: # 如果大于这一行最后一个元素值,那么就下一行
  15. continue
  16. return False