二維數組中的查找
面試題3:
似題:
我做過這個類似的有楊氏矩陣為背景的,實際上是一樣的
暴力遍歷
二維數組暴力遍歷的話時間復雜度為O(n2)
雖然暴力但是應付學校考試這個就是一把好手
#include<stdio.h> //const 就是因為二維數組是定死的 int search(const int arr[4][4], int num,unsigned int* prow,unsigned int* pcol) { int i = 0; //掃描行 for (i = 0; i < *prow; i++) { //掃描列 int j = 0; for (j = 0; j < *pcol; j++) { //與所查數比較判斷,有一樣的就直接返回 if (arr[i][j] == num) { *prow = i;//把坐標傳回去 *pcol = j; return 1;//一次返回,之后就不看了,因為已經證明到有這個數了,沒必要在做無用功了 } } } return 0; } int main() { int arr[4][4] = { {1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15} }; int num = 0; while (1) { unsigned int row = sizeof(arr) / sizeof(arr[0]); unsigned int col = sizeof(arr[0]) / sizeof(arr[0][0]); //把row,col拉進來就是為了每次再來是更新一次 //長寬,因為下面我們就是用row,col變量沒有用其他變量 printf("請輸入你想要找的數:>"); scanf("%d", &num); if (search(arr, num, &row, &col))//把長寬傳地址過去用指針prow,pcol接收 { printf("有這個數\n"); printf("坐標為(%d,%d)\n", row, col); } else { printf("沒有這個數\n"); } } return 0; }
動態基點操作
暴力操作肯定拿不下面試官的心,沒有思想,應該優化程序,減小時間復雜度
然后把上面search函數改改就可以了
時間復雜度也降為O(n)
#include<stdio.h> //const 就是因為二維數組是定死的 int search(const int arr[4][4], int num,unsigned int* prow,unsigned int* pcol) { int i = 0; unsigned int x = 0; unsigned int y = *pcol-1; while ((x<*prow)&&(y>=0)) { if (arr[x][y] - num > 0) { y--; } else if (arr[x][y] - num < 0) { x++; } else { *prow = x; *pcol = y; return 1; } } return 0; } int main() { int arr[4][4] = { {1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15} }; int num = 0; while (1) { unsigned int row = sizeof(arr) / sizeof(arr[0]); unsigned int col = sizeof(arr[0]) / sizeof(arr[0][0]); //把row,col拉進來就是為了每次再來是更新一次 //長寬,因為下面我們就是用row,col變量沒有用其他變量 printf("請輸入你想要找的數:>"); scanf("%d", &num); if (search(arr, num, &row, &col))//把長寬傳地址過去用指針prow,pcol接收 { printf("有這個數\n"); printf("坐標為(%d,%d)\n", row, col); } else { printf("沒有這個數\n"); } } return 0; }
結果也是不錯的
以上就是C語言面試C++二維數組中的查找示例的詳細內容,更多關于C++二維數組中的查找的資料請關注服務器之家其它相關文章!
原文鏈接:https://blog.csdn.net/diandengren/article/details/120226553