編寫一個高效的算法來搜索 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。
採用的二分法。整個矩陣分成了M*N一維數組,拆分爲在for循環下的一維數組。題意就成爲了一維數組中查找。二分法將數組一分爲二。判斷在左邊還是右邊。接着縮短邊界在二分。直到找到。
public class Solution {
public bool SearchMatrix(int[,] matrix, int target) {
if (matrix.Length == 0) return false;
int row = matrix.GetLength(0);
int col = matrix.GetLength(1);
for (int i = 0; i < row; i++)
{
int left = 0;
int right = col - 1;
while (left <= right)
{
int mid = (left + right) / 2;
if (matrix[i, mid] == target) return true;
if (matrix[i, mid] < target) left = mid + 1;//說明target不在左邊
else right = mid - 1;//說明target不在右邊邊
}
}
return false;
}
}
第二種方法。數據是有序排列,採用剪枝,選取起點
選左上角,往右走和往下走都增大,不能選
選右下角,往上走和往左走都減小,不能選
選左下角,往右走增大,往上走減小,可選
選右上角,往下走增大,往左走減小,可選
public class Solution {
public bool SearchMatrix(int[,] matrix, int target) {
if (matrix.Length == 0) return false;
int row = matrix.GetLength(0)-1;
int col = 0;
while (row>=0 &&col<matrix.GetLength(1))
{
if (matrix[row,col] == target)
{
return true;
}
else if (matrix[row,col] > target)
{
row--;
}
else if(matrix[row,col] < target)
{
col++;
}
}
return false;
}
}