《剑指offer》第四题(二维数组中的查找)
生活随笔
收集整理的這篇文章主要介紹了
《剑指offer》第四题(二维数组中的查找)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
// 二維數組中的查找
// 題目:在一個二維數組中,每一行都按照從左到右遞增的順序排序,每一列都按
// 照從上到下遞增的順序排序。請完成一個函數,輸入這樣的一個二維數組和一個
// 整數,判斷數組中是否含有該整數。
#include <iostream>
using namespace std;bool serach_in(int* matrix, int rows, int cols, int number)
{bool flag = false;if ((matrix != NULL) && (rows > 0) && (cols > 0))//判斷不能忘
{int row = 0, col = cols - 1;while ((row < rows) && (col >= 0)){if (matrix[row*cols + col] == number){flag = true;break;}else if (matrix[row*cols + col] > number)//用實例分析過程,思想比程序更重要col--;elserow++;}}return flag;
}void test1()//要查找的數在數組中
{cout << "Test1:\n";int matrix[][4] = { {1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15} };bool result;result = serach_in(matrix[0], 4, 4, 7);if (result)cout << "Yes!\n";elsecout << "No!\n";
}void test2()//要查找的數不在數組中
{cout << "Test2:\n";int matrix[][4] = { {1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15} };bool result;result = serach_in(matrix[0], 4, 4, 14);if (result)cout << "Yes!\n";elsecout << "No!\n";
}void test3()//要查找的數是數組中最小的數字
{cout << "Test3:\n";int matrix[][4] = { {1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15} };bool result;result = serach_in(matrix[0], 4, 4, 1);if (result)cout << "Yes!\n";elsecout << "No!\n";
}void test4()//要查找的數是數組中最大的數字
{cout << "Test4:\n";int matrix[][4] = { {1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15} };bool result;result = serach_in(matrix[0], 4, 4, 15);if (result)cout << "Yes!\n";elsecout << "No!\n";
}void test5()//要查找的數比數組中最小的數字還小
{cout << "Test5:\n";int matrix[][4] = { {1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15} };bool result;result = serach_in(matrix[0], 4, 4, 0);if (result)cout << "Yes!\n";elsecout << "No!\n";
}void test6()//要查找的數比數組中最大的數字還大
{cout << "Test6:\n";int matrix[][4] = { {1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15} };bool result;result = serach_in(matrix[0], 4, 4, 16);if (result)cout << "Yes!\n";elsecout << "No!\n";
}void test7()//魯棒性測試,輸入空指針
{cout << "Test6:\n";bool result;result = serach_in(NULL, 0, 0, 1);if (result)cout << "Yes!\n";elsecout << "No!\n";
}int main()
{test1();test2();test3();test4();test5();test6();test7();//重點,魯棒性測試
system("pause");
}
?
轉載于:https://www.cnblogs.com/CJT-blog/p/10458767.html
總結
以上是生活随笔為你收集整理的《剑指offer》第四题(二维数组中的查找)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: EBS并发管理器启动失败,系统暂挂,在重
- 下一篇: PHPStorm默认在新窗口打开