剑指Offer 面试题4:二维数组中的查找
2020-06-29 04:57
1146 查看
面试题4:二维数组中的查找
题目:
在一个二维数组中,每一行都按照从左到右递增,每一列也按照从上到下递增,输入一个这样的二维数组和一个整数,判断数组中是否有这个数
- 思路:
以整个可搜索趋于的左下角数字为判定基准,如果等于那么返回true,如果小于,那么当前列向右推进一列,如果大于,当前行向上推进一行,直至行和列超出范围值结束循环
#include "stdafx.h" bool Find(int * matrix, int cols, int rows, int Num) { if (matrix == nullptr || cols < 1 || rows < 1) return false; bool HaveNum = false; int currentcols = 0; int currentrows = rows-1; while (currentrows >=0 &¤tcols < cols) { if (matrix[currentrows*cols + currentcols] == Num) { HaveNum = true; break; } else if (matrix[currentrows*cols + currentcols] < Num) currentcols++; else currentrows--; } return HaveNum; } // ====================测试代码==================== void Test(char* testName, int* matrix, int rows, int columns, int number, bool expected) { if (testName != nullptr) printf("%s begins: ", testName); bool result = Find(matrix, rows, columns, number); if (result == expected) printf("Passed.\n"); else printf("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", nullptr, 0, 0, 16, false); } int main(int argc, char* argv[]) { Test1(); Test2(); Test3(); Test4(); Test5(); Test6(); Test7(); return 0; }
相关文章推荐
- 《剑指Offer》面试题-二维数组中的查找
- 《剑指Offer》面试题-二维数组中的查找
- 剑指offer面试题03:二维数组中的查找
- 剑指Offer面试题:2.二维数组中的查找
- 剑指offer面试题3-二维数组查找问题
- 剑指offer-面试题4:二维数组中的查找 解法
- 《剑指Offer》面试题3:二维数组中的查找(行列分别有序数组的二分查找)
- (剑指Offer)面试题03. 数组中重复的数字&面试题04. 二维数组中的查找
- 《剑指Offer》面试题三之二维数组中的查找
- 剑指offer——面试题3:二维数组的查找
- 剑指offer面试题3—二维数组中的查找
- 《剑指offer》面试题3:二维数组中的查找
- 剑指Offer面试题4:---数组之(二维数组中的查找)
- 《剑指offer》面试题04:二维数组中的查找
- 九度《剑指Offer》面试题3 二维数组中的查找
- 《剑指Offer》学习笔记--面试题3:二维数组中的查找
- 剑指offer 面试题3:二维数组中的查找
- 《剑指offer》 面试题04.二维数组中的查找
- 剑指offer 面试题3:二维数组中查找
- 剑指offer 面试题4 二维数组的查找