【LeetCode】240. Search a 2D Matrix II 解题记录
问题描述
Write an efficient algorithm that searches for a target value in an m x n integer matrix. The 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.
测试样例
1 | Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5 |
1 | Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20 |
说明
1 | m == matrix.length |
解题
思路
取最左下方元素为基准 pivot,
-
若 pivot 值比目标小,则目标在其右侧,横坐标右移一位
-
若 pivot 值比目标大,则目标在其上侧,纵坐标上移一位
补充:
- 时间复杂度
O(logn)
代码
1 | class Solution { |
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 哆啦 C 梦!
评论