int[][] matrix = { new int[] { 1, 4, 7, 11, 15 }, new int[] { 2, 5, 8, 12, 19 }, new int[] { 3, 6, 9, 16, 22 }, new int[] { 10, 13, 14, 17, 24 }, new int[] { 18, 21, 23, 26, 30 } };
searchTarget(matrix, 18);

 

/// <summary>
/// 在行递增同时列递增的二维数组中查找某个值是否存在
/// 从右上角开始走,利用这个顺序关系可以在O(m+n)的复杂度下解决这个题:
/// 如果当前位置元素比target小,则row++
/// 如果当前位置元素比target大,则col--
/// 如果相等,返回true
/// 如果越界了还没找到,说明不存在,返回false
/// </summary>
/// <param name="matric"></param>
/// <param name="target"></param>
public static bool searchTarget(int[][] matrix, int target)
{
int row = 0;
int col = matrix[0].Length - 1;
int rowLength = matrix.Length - 1;
while (row <= rowLength && col >= 0)
{
if (matrix[row][col] > target)
{
col--;
}
else if (matrix[row][col] < target)
{
row++;
}
else
{
return true;
}
}
return false;
}