搜索二维矩阵
Category Difficulty Likes Dislikes
algorithms Medium (46.78%) 572 -
Tags
Companies
编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:
每行中的整数从左到右按升序排列。
每行的第一个整数大于前一行的最后一个整数。
示例 1:
1 3 5 7
10 11 16 20
23 30 34 60
输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
输出:true
示例 2:
1 3 5 7
10 11 16 20
23 30 34 60
输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
输出:false
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 100
-104 <= matrix[i][j], target <= 104
Discussion | Solution
class Solution {
public:
// 根据题意,可以将二维转化为一维,然后进行二分
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int n = matrix.size(), m = matrix[0].size();
int l = 0, r = n*m-1;
while(l <= r)
{
int mid = l + ((r-l)>>1);
int i = mid/m, j=mid%m;
if(matrix[i][j] == target)
return true;
else if(matrix[i][j] < target)
l = mid + 1;
else
r = mid - 1;
}
return false;
}
};
标签:20,matrix,leetcode74,int,30,60,target
From: https://www.cnblogs.com/jinjidelei/p/16889245.html