马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
Problem
Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:
- Integers in each row are sorted in ascending from left to right.
- Integers in each column are sorted in ascending from top to bottom.
Algorithm
Choose the top-right corner (or bottom-left corner) as the starting position, and then repeat the following process:
- If the current element is equal to the target, then end.
- If the current element is greater than the target, all elements to the bottom-right are larger, so move left.
- If the current element is smaller than the target, all elements to the top-left are smaller, so move down.
The time complexity is O ( m + n ) O(m+n) O(m+n).
Code
- class Solution:
- def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
- if not matrix or not matrix[0]:
- return False
-
- rows, cols = len(matrix), len(matrix[0])
- r, c = 0, cols-1
- while r < rows and c >= 0:
- if matrix[r][c] == target:
- return True
- elif matrix[r][c] > target:
- c -= 1
- else:
- r += 1
-
- return False
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |