题目描述
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
- Integers in each row are sorted from left to right.
- The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
Given target =3, returntrue.
思路:
思路1:二分法确定target可能在第几行出现。再用二分法在该行确定target可能出现的位置。时间复杂度O(logn+logm)
思路2:从右上角元素开始遍历,每次遍历中若与target相等则返回true;若小于则行向下移动;若大于则列向左移动。时间复杂度m+n
思路1代码:
class Solution {
public:
bool searchMatrix(vector<vector<int> > &matrix, int target) {
int left = 0;
int right = matrix.size()-1;
if(left != right)
{
while(left<=right)
{
int middle = left + (right-left)/2;
if(matrix[middle][0] < target)
{
left = middle+1;
}
else if(matrix[middle][0] > target)
{
right = middle-1;
}
else
{
return true;
}
}
}
if(right == -1)
{
return false;
}
else
{
int row = right;
int left = 0;
int right = matrix[row].size()-1;
while(left<=right)
{
int middle = left + (right-left)/2;
if(matrix[row][middle] < target)
{
left = middle+1;
}
else if(matrix[row][middle] > target)
{
right = middle-1;
}
else
{
return true;
}
}
return false;
}
}
};
思路2代码:
package com.leetcode;
public class SearchMatrix {
public boolean searchMatrix(int[][] matrix, int target) {
int n = matrix.length;
int m = matrix[0].length;
int i = n - 1;
int j = 0;
while (j < m && i >= 0) {
if (matrix[i][j] > target) {
i--;
} else if (matrix[i][j] < target) {
j++;
} else {
return true;
}
}
return false;
}
}