AIRobot

AIRobot quick note


  • 首页

  • 关于

  • 标签

  • 分类

  • 归档

  • 搜索

LeetCode 240 搜索二维矩阵 II

发表于 2019-03-06 分类于 algorithm
本文字数: 888 阅读时长 ≈ 1 分钟
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:

每行的元素从左到右升序排列。
每列的元素从上到下升序排列。
示例:

现有矩阵 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,返回 true。

给定 target = 20,返回 false。

如代码,如果target小于当前值,则列坐标-1,否则如果target大于当前值,则行坐标+1。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(matrix.size()==0||matrix[0].empty())
return false;
int m = matrix.size();
int n = matrix[0].size();
int row = 0;
int col = n-1;
while(row<m&&col>=0)
{
if(target<matrix[row][col])
--col;
else if(target>matrix[row][col])
++row;
else
return true;
}
return false;
}
};
# LeetCode
LeetCode 169 求众数
LeetCode 88 合并两个有序数组
AIRobot

AIRobot

AIRobot quick note
130 日志
15 分类
23 标签
GitHub E-Mail
Creative Commons
0%
© 2023 AIRobot | 716k | 10:51