剑指offer笔记面试题4----二维数组中的查找

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

测试用例:

  • 二维数组中包含查找的数字(查找的数字是数组中的最大值和最小值;查找的数字介于数组中的最大值和最小值之间)。
  • 二维数组中没有查找的数字(查找的数字大于数组中的最大值;查找的数字小于数组中的最小值;查找的数字在数组的最大值和最小值之间但数组中没有这个数字)。
  • 特殊输入测试(输入空指针)。

测试代码:

/*
***数字包含在数组中(为数组中的最大值或最小值或介于最大与最小之间)
***数字不包含在数组中(大于最大值或小于最小值或介于最大与最小之间但不包含)
***输入数组为空指针 
*/
void test(char* testName, int* matrix, int rows, int columns, int number, bool expected){
    if(testName != nullptr){
        printf("%s begins: ", testName);
    }
    bool result = find(matrix, rows, columns, number);
    if(result == expected){
        printf("Passed.\n");
    }
    else{
        printf("Failed.\n");
    }
} 

/*******数组********/ 
// 1 2 8 9
// 2 4 9 12
// 4 7 10 13
// 6 8 11 15
int matrix[][4] = {{1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15}};

//要查找的数在数组中
void test1(){
    test("test1", (int*)matrix, 4, 4, 7, true);
} 

//要查找的数不在数组中
void test2(){
    test("test2", (int*)matrix, 4, 4, 5, false);
} 

//要查找的数是数组中最小的数字
void test3(){
    test("test3", (int*)matrix, 4, 4, 1, true);
} 

//要查找的数是数组中的最大的数字
void test4(){
    test("test4", (int*)matrix, 4, 4, 15, true);
} 

//要查找的数比数组中最小的数字还小
void test5(){
    test("test5", (int*)matrix, 4, 4, 0, false);
} 

//要查找的数比数组中最大的数字还大
void test6(){
    test("test6", (int*)matrix, 4, 4, 16, false);
} 

//鲁棒性测试,输入空指针
void test7(){
    test("test7", nullptr, 0, 0, 16, false);
} 

本题考点:

  • 考查应聘者对二维数组的理解及编程能力。二维数组在内存中占据连续的空间。在内存中从上到下存储各行元素,在同一行中按照从左到右的顺序存储。因此我们可以根据行号和列号计算出相对于数组首地址的偏移量,从而找到对应的元素。
  • 考查应聘者分析问题的能力。当应聘者发现问题比较复杂时,能不能通过具体的例子找出其中的规律,是能否解决这个问题的关键所在。这个题目只要从一个具体的二维数组的右上角开始分析,就能找到查找的规律,从而找到解决问题的突破口。

实现代码:

#include <cstdio>

bool find(int* matrix, int rows, int columns, int number){
    bool found = false;
    if(matrix != nullptr && rows > 0 && columns > 0){
        int row = 0;
        int column = columns - 1;
        while(row < rows && column >= 0){
            if(matrix[row*columns+column] == number){
                found = true;
                break;
            }
            else if(matrix[row*columns+column] > number){
                column--;
            }
            else{
                row++;
            }
        }
    }
    return found;
}
int main(){
    test1();
    test2();
    test3();
    test4();
    test5();
    test6();
    test7();
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/tangliang39/p/11694332.html