3 二维数组中的查找

  

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

1 2 8 9
2 4 9 12
4 7 10 11
6 8 11 15

 

C++:

 1 class Solution {
 2 public:
 3     bool Find(int target, vector<vector<int> > array) {
 4         int n = array.size() ;
 5         int m = array[0].size() ;
 6         if (array.empty() || n == 0 || m == 0)
 7             return false ;
 8         int r = 0 ;
 9         int c = m - 1;
10         while(r < n && c >= 0){
11             if (array[r][c] == target){
12                 return true ;
13             }else if (array[r][c] > target){
14                 c-- ;
15             }else{
16                 r++ ;
17             }
18         }
19         return false ;
20     }
21 };

 

 

c++:

 1 bool Find(int * arr , int rows , int cols , int num){
 2     bool found = false ;
 3     if (arr != NULL && rows >0 && cols >0){
 4         int r = 0 ;
 5         int c = cols - 1 ;
 6         while(r < rows && c >= 0){
 7             if (arr[r*cols+c] == num){
 8                 found = true ;
 9                 break ;
10             }
11             else if (arr[r*cols+c] > num)
12                 c-- ;
13             else
14                 r++ ;
15         }
16     }
17     return found ;
18 }

 

java:

 1 public class Solution {
 2     public boolean Find(int target, int [][] array) {
 3         int n = array.length ;
 4         int m = array[0].length ;
 5         int i = 0 ;
 6         int j = m-1 ;
 7         while(i < n && j >= 0){
 8             if (target == array[i][j])
 9                 return true ;
10             else if (target < array[i][j])
11                 j-- ;
12             else
13                 i++ ;
14         }
15         return false ;
16     }
17 }

 

posted @ 2017-11-10 15:43  __Meng  阅读(160)  评论(0编辑  收藏  举报