面试题4:二维数组中的查找
生活随笔
收集整理的這篇文章主要介紹了
面试题4:二维数组中的查找
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
/******************************************************************* Copyright(c) 2018, htfeng All rights reserved. *******************************************************************///================================================================== // 《劍指Offer——名企面試官精講典型編程題》代碼 // 作者:何海濤 // C++ //==================================================================// 面試題4:二維數組中的查找 // 題目:在一個二維數組中,每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。 // 請完成一個函數,輸入這樣的一個二維數組和一個整數,判斷數組中是否含有該整數#include<iostream>using namespace std;bool Find(int *matrix, int rows, int columns, int numbers) {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] == numbers) {found = true;break;}else if (matrix[row*columns + column] > numbers)--column;else++row;}}return found; }//===============================測試==================================== void Test(char* testName, int* matrix, int rows, int columns, int numbers, bool expected) {if (testName != nullptr)printf("%s begins: ", testName);bool result = Find(matrix, rows, columns, numbers);if (result == expected)printf("Passed.\n");elseprintf("Failed.\n"); }// 二維數組中包含查找的數字 void test1() {int matrix[][4] = { {1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15} };int *test = (int*) matrix;cout << test[10] << endl;char test1[] = "Test1";Test(test1, (int*)matrix, 4, 4, 7, true); }// 二維數組中沒有查找的數字 void test2() {int matrix[][4] = { {1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15} };int *test = (int*)matrix;char test2[] = "Test2";Test(test2, (int*)matrix, 4, 4, 14, false); }// 特殊輸入測試 void test3() {char test3[] = "Test3";Test(test3, nullptr, 0, 0, 16, false); }int main() {test1();test2();test3();system("pause");return 0; }轉載于:https://www.cnblogs.com/htfeng/p/9931730.html
總結
以上是生活随笔為你收集整理的面试题4:二维数组中的查找的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python:每日一题002
- 下一篇: c语言,如何产生随机数