题解 | #寻找牛群中的特定编号牛#
寻找牛群中的特定编号牛
https://www.nowcoder.com/practice/e0c6f3fba6dd40b99e8bcc0241631f9d
- 题目考察的知识点 : 二分查找
- 题目解答方法的文字分析:
- 从矩阵的右上角开始搜索。
- 如果当前位置的值等于 target,则返回 true;
- 如果当前位置的值大于 target,说明 target 只可能在当前位置的左边或下边,将搜索位置移动到当前位置的左边;
- 如果当前位置的值小于 target,说明 target 只可能在当前位置的下边或右边,将搜索位置移动到当前位置的下边;
- 当搜索位置越界时,说明没有找到 target,返回 false
- 本题解析所用的编程语言:Python
- 完整且正确的编程代码
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param matrix int整型二维数组 # @param target int整型 # @return bool布尔型 # class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: start = 0 end = len(matrix[0]) - 1 while start < len(matrix) and end >= 0: if target > matrix[start][end]: end = end - 1 elif target < matrix[start][end]: start = start + 1 else: return True return False
牛客高频top202题解系列 文章被收录于专栏
记录刷牛客高频202题的解法思路