C語言面試C++二維數(shù)組中的查找示例
二維數(shù)組中的查找
面試題3:
似題:
我做過這個(gè)類似的有楊氏矩陣為背景的,實(shí)際上是一樣的
暴力遍歷
二維數(shù)組暴力遍歷的話時(shí)間復(fù)雜度為O(n2)
雖然暴力但是應(yīng)付學(xué)校考試這個(gè)就是一把好手
#include<stdio.h> //const 就是因?yàn)槎S數(shù)組是定死的 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++) { //與所查數(shù)比較判斷,有一樣的就直接返回 if (arr[i][j] == num) { *prow = i;//把坐標(biāo)傳回去 *pcol = j; return 1;//一次返回,之后就不看了,因?yàn)橐呀?jīng)證明到有這個(gè)數(shù)了,沒必要在做無用功了 } } } 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拉進(jìn)來就是為了每次再來是更新一次 //長寬,因?yàn)橄旅嫖覀兙褪怯胷ow,col變量沒有用其他變量 printf("請輸入你想要找的數(shù):>"); scanf("%d", &num); if (search(arr, num, &row, &col))//把長寬傳地址過去用指針prow,pcol接收 { printf("有這個(gè)數(shù)\n"); printf("坐標(biāo)為(%d,%d)\n", row, col); } else { printf("沒有這個(gè)數(shù)\n"); } } return 0; }
動(dòng)態(tài)基點(diǎn)操作
暴力操作肯定拿不下面試官的心,沒有思想,應(yīng)該優(yōu)化程序,減小時(shí)間復(fù)雜度
然后把上面search函數(shù)改改就可以了
時(shí)間復(fù)雜度也降為O(n)
#include<stdio.h> //const 就是因?yàn)槎S數(shù)組是定死的 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拉進(jìn)來就是為了每次再來是更新一次 //長寬,因?yàn)橄旅嫖覀兙褪怯胷ow,col變量沒有用其他變量 printf("請輸入你想要找的數(shù):>"); scanf("%d", &num); if (search(arr, num, &row, &col))//把長寬傳地址過去用指針prow,pcol接收 { printf("有這個(gè)數(shù)\n"); printf("坐標(biāo)為(%d,%d)\n", row, col); } else { printf("沒有這個(gè)數(shù)\n"); } } return 0; }
結(jié)果也是不錯(cuò)的
以上就是C語言面試C++二維數(shù)組中的查找示例的詳細(xì)內(nèi)容,更多關(guān)于C++二維數(shù)組中的查找的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C語言實(shí)現(xiàn)手寫Map(全功能)的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何利用C語言實(shí)現(xiàn)手寫Map(全功能),文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)C語言有一定幫助,需要的可以參考一下2022-08-08深入探究C/C++中互斥量(鎖)的實(shí)現(xiàn)原理
? 互斥量是一種同步原語,用于保護(hù)多個(gè)線程同時(shí)訪問共享數(shù)據(jù),互斥量提供獨(dú)占的、非遞歸的所有權(quán)語義,本文將和大家一起深入探究C/C++中互斥量(鎖)的實(shí)現(xiàn)原理,感興趣的小伙伴跟著小編一起來看看吧2024-06-06C++回調(diào)函數(shù)實(shí)現(xiàn)計(jì)算器和qsort
這篇文章主要介紹了C++回調(diào)函數(shù)實(shí)現(xiàn)計(jì)算器和qsort,回調(diào)函數(shù)就是一個(gè)通過函數(shù)指針調(diào)用的函數(shù)。如果你把函數(shù)的指針(地址)作為參數(shù)傳遞給另一個(gè)函數(shù),當(dāng)這個(gè)指針被用來調(diào)用其所指向的函數(shù)時(shí),我們就說這是回調(diào)函數(shù)2022-08-08c++ 一個(gè)二進(jìn)制串轉(zhuǎn)化為整數(shù)的解決方法
以下是將一個(gè)二進(jìn)制串轉(zhuǎn)化為整數(shù)的實(shí)例。需要的朋友參考下2013-05-05C++可變參數(shù)的函數(shù)與模板實(shí)例分析
這篇文章主要介紹了C++可變參數(shù)的函數(shù)與模板,非常重要的概念,需要的朋友可以參考下2014-08-08