【面试题3】二维数组中的查找

【题目描述】

在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样一个二维数组和一个整数,判断数组中是否存在该整数。

【解决方案】

每次根据右上角的一个数arr[i][j]和所求整数num的比较结果,来排除一行(或一列)的整数。

arr[i][j] == num,数组中数组中存在该整数;

arr[i][j] > num,arr[i][j]所在列都比num大,排除arr[i][j]所在列;

arr[i][j] < num,arr[i][j]所在行都比num小,排除arr[i][j]所在行; 

我的代码实现,仅供参考:

 1         public bool IsExists(int[][] arr, int num)
 2         {
 3             if (arr == null || arr[0] == null)
 4                 return false;
 5 
 6             int row = 0;
 7             int rows = arr[0].Length;
 8             int col = arr.GetLength(0) - 1;
 9 
10             while (row < rows && col >= 0)
11             {
12                 if (arr[row][col] > num)
13                 {
14                     col--;
15                 }
16                 else if (arr[row][col] < num)
17                 {
18                     row++;
19                 }
20                 else if (arr[row][col] == num)
21                 {
22                     return true;
23                 }
24             }
25 
26             return false;
27         }
原文地址:https://www.cnblogs.com/HuoAA/p/4796850.html