LeetCode Algorithm 240. 搜索二维矩阵 II
生活随笔
收集整理的這篇文章主要介紹了
LeetCode Algorithm 240. 搜索二维矩阵 II
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
240. 搜索二維矩陣 II
Ideas
這題我記得在左神算法初級班里面有。
主要的思想就是定義兩個指針row_index和col_index,從右上角開始逐個搜索。
如果matrix[row_index][col_index] < target,說明當(dāng)前遍歷的元素比較小,需要往下一行去搜索。
如果matrix[row_index][col_index] > target,說明當(dāng)前遍歷的元素比較大,需要往前一列去搜索。
如果matrix[row_index][col_index] == target,說明找到了,直接返回True。
最后如果兩個指針越界了那就說明target不在matrix中,返回False。
為什么從右上角開始逐個搜索而不是從左上角開始搜索呢?
假如從左上角開始搜索,因為matrix[0][0]位置的元素是最小的,所以如果matrix[row_index][col_index] < target,那么到底是往下一列走還是往下一行走呢,不好確定,所以從右上角開始搜索。
Code
Python
from typing import Listclass Solution:def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:rows, cols = len(matrix), len(matrix[0])row_index, col_index = 0, cols - 1while row_index < rows and col_index > -1:if matrix[row_index][col_index] < target:row_index += 1elif matrix[row_index][col_index] > target:col_index -= 1else:return Truereturn False總結(jié)
以上是生活随笔為你收集整理的LeetCode Algorithm 240. 搜索二维矩阵 II的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2019年第十届蓝桥杯 - 省赛 - C
- 下一篇: LeetCode 多线程 1117. H