日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

03_FindInPartiallySortedMatrix.cpp

發布時間:2023/12/20 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 03_FindInPartiallySortedMatrix.cpp 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

代碼來自劍指offer,詳細解釋如下:

#include<iostream> using namespace std;// 二維數組matrix中,每一行都從左到右遞增排序, // 每一列都從上到下遞增排序 bool Find(int* matrix, int rows, int columns, int number) {bool found = false;if (matrix != NULL && 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; }// ====================測試代碼==================== void Test(char* testName, int* matrix, int rows, int columns, int number, bool expected) {if (testName != NULL)printf("%s begins: ", testName);bool result = Find(matrix, rows, columns, number);if (result == expected)printf("Passed.\n");elseprintf("Failed.\n"); }// 1 2 8 9 // 2 4 9 12 // 4 7 10 13 // 6 8 11 15 // 要查找的數在數組中 void Test1() {int matrix[][4] = { { 1, 2, 8, 9 },{ 2, 4, 9, 12 },{ 4, 7, 10, 13 },{ 6, 8, 11, 15 } };Test("Test1", (int*)matrix, 4, 4, 7, true); }// 1 2 8 9 // 2 4 9 12 // 4 7 10 13 // 6 8 11 15 // 要查找的數不在數組中 void Test2() {int matrix[][4] = { { 1, 2, 8, 9 },{ 2, 4, 9, 12 },{ 4, 7, 10, 13 },{ 6, 8, 11, 15 } };Test("Test2", (int*)matrix, 4, 4, 5, false); }// 1 2 8 9 // 2 4 9 12 // 4 7 10 13 // 6 8 11 15 // 要查找的數是數組中最小的數字 void Test3() {int matrix[][4] = { { 1, 2, 8, 9 },{ 2, 4, 9, 12 },{ 4, 7, 10, 13 },{ 6, 8, 11, 15 } };Test("Test3", (int*)matrix, 4, 4, 1, true); }// 1 2 8 9 // 2 4 9 12 // 4 7 10 13 // 6 8 11 15 // 要查找的數是數組中最大的數字 void Test4() {int matrix[][4] = { { 1, 2, 8, 9 },{ 2, 4, 9, 12 },{ 4, 7, 10, 13 },{ 6, 8, 11, 15 } };Test("Test4", (int*)matrix, 4, 4, 15, true); }// 1 2 8 9 // 2 4 9 12 // 4 7 10 13 // 6 8 11 15 // 要查找的數比數組中最小的數字還小 void Test5() {int matrix[][4] = { { 1, 2, 8, 9 },{ 2, 4, 9, 12 },{ 4, 7, 10, 13 },{ 6, 8, 11, 15 } };Test("Test5", (int*)matrix, 4, 4, 0, false); }// 1 2 8 9 // 2 4 9 12 // 4 7 10 13 // 6 8 11 15 // 要查找的數比數組中最大的數字還大 void Test6() {int matrix[][4] = { { 1, 2, 8, 9 },{ 2, 4, 9, 12 },{ 4, 7, 10, 13 },{ 6, 8, 11, 15 } };Test("Test6", (int*)matrix, 4, 4, 16, false); }// 魯棒性測試,輸入空指針 void Test7() {Test("Test7", NULL, 0, 0, 16, false); }int main() {Test1();Test2();Test3();Test4();Test5();Test6();Test7();//下面一段代碼非常有意思,是從上面拷貝下來的☆☆☆☆☆☆☆☆☆☆//它顯示:如果使用(int*對matrix進行強制轉化,二維數組就會被flatten(也就是打散),變成一維數組int matrix[][4] = { { 1, 2, 8, 9 },{ 2, 4, 9, 12 },{ 4, 7, 10, 13 },{ 6, 8, 11, 15 } };int *p = (int*)matrix;cout << p[7] << endl;cin.get();cin.get();return 0; }//整個代碼的意思就是找目標數的時候,從右上角往左下角尋找,逐步縮小搜索范圍。

總結

以上是生活随笔為你收集整理的03_FindInPartiallySortedMatrix.cpp的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。