(说明:本博客中的题目题目详细说明参考代码均摘自 “何海涛《剑指Offer:名企面试官精讲典型编程题》2012年”)

题目

  在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断是否含有该整数。

  进一步的详细说明:

  下图中的二维数组就是每行、每列都递增排序。如果在这个数组中查找数字 7,则返回 true;如果查找数字 5,由于数组不含有该数字,则返回 false。

算法设计思想

  对于类似上图中的二维数组,选择从右上方(数字 9)或 左下方(数字 6)开始遍历,这样可以保证向单一方向缩小搜索范围;而从左上方(数字 1)或右下方(数字 15)开始遍历,可以朝两个方向进行进一步搜索,从而导致无法缩小范围。

以查找数字 5 为例,
  若从左下方(数字 6)开始遍历,则由于数字 5 < 6 ,根据二维数组沿行从左到右递增,沿列从上到下递增,数字 5 可能位于数字 6 的上方或左侧,而数字 6 的左侧无元素,因此数字 5 只能位于数字 6 的上方,从而缩小了搜索范围;
  若从左上方(数字 1)开始遍历,则由于数字 5 > 1,根据二维数组沿行从左到右递增,沿列从上到下递增,数字 5 可能位于数字 1 的下方或右侧,而数字 1的下方和右侧均有元素,因此无法缩小搜索范围。

  以上说明,找到一个好的起点很重要,其会直接影响算法的可行性。

C++ 实现

  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. // Try to find 'target' from 'matrix' with 'rows' rows and 'cols' columns,
  6. // If found, return true; else return false
  7. bool Find(int* matrix, int rows, int cols, int target)
  8. {
  9. bool found = false;
  10.  
  11. if (!matrix || rows < || cols < ) // 易漏点
  12. return found;
  13. int i = ;
  14. int j = cols-; // Note: the index of the last element in each row is cols-1. // 易错点
  15. while ((i < rows) && (j >= ))
  16. {
  17. int current = *(matrix+i*cols+j);
  18.  
  19. if (target < current)
  20. j--;
  21. else if (target > current)
  22. i++;
  23. else { // target == current
  24. found = true;
  25. break;
  26. }
  27. }
  28.  
  29. return found;
  30. }
  31.  
  32. // Display the result whether the target is found.
  33. void display(int* matrix, int rows, int cols, int target)
  34. {
  35. cout << "Target " << target << " is ";
  36. if (Find(matrix, rows, cols, target))
  37. cout << "";
  38. else
  39. cout << "not ";
  40. cout << "found." << endl;
  41. }
  42.  
  43. void unitest()
  44. {
  45. int mat[] = {, , , ,
  46. , , , ,
  47. , , , ,
  48. , , , };
  49. // Try to find digits 7 and 5, then display the result
  50. display(mat, , , );
  51. display(mat, , , );
  52. }
  53.  
  54. int main()
  55. {
  56. unitest();
  57. return ;
  58. }

Python 实现

  1. #!/usr/bin/python
  2. # -*- coding: utf8 -*-
  3.  
  4. # Try to find 'target' from 'matrix' with 'rows' rows and 'cols' columns,
  5. # If found, return true; else return false
  6. def find_target(matrix, rows, cols, target):
  7. found = False
  8. if not matrix or rows < 0 or cols < 0: # 易漏点
  9. return found
  10. i, j = 0, cols-1 # 易错点
  11. while i < rows and j >= 0:
  12. current = matrix[i*cols+j]
  13. if target < current:
  14. j -= 1
  15. elif target > current:
  16. i += 1
  17. else: # target == current
  18. found = True
  19. break
  20.  
  21. return found
  22.  
  23. def unitest():
  24. mat = [1, 2, 8, 9,
  25. 2, 4, 9, 12,
  26. 4, 7, 10, 13,
  27. 6, 8, 11, 15]
  28. # Try to find digits 7 and 5, then display the result
  29. for target in [7, 5]:
  30. print "Target %d is %s found." % (target, "" if find_target(mat, 4, 4, target) else "not")
  31.  
  32. if __name__ == "__main__":
  33. unitest()

参考代码

1. targetver.h

  1. #pragma once
  2.  
  3. // The following macros define the minimum required platform. The minimum required platform
  4. // is the earliest version of Windows, Internet Explorer etc. that has the necessary features to run
  5. // your application. The macros work by enabling all features available on platform versions up to and
  6. // including the version specified.
  7.  
  8. // Modify the following defines if you have to target a platform prior to the ones specified below.
  9. // Refer to MSDN for the latest info on corresponding values for different platforms.
  10. #ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista.
  11. #define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows.
  12. #endif

2. stdafx.h

  1. // stdafx.h : include file for standard system include files,
  2. // or project specific include files that are used frequently, but
  3. // are changed infrequently
  4. //
  5.  
  6. #pragma once
  7.  
  8. #include "targetver.h"
  9.  
  10. #include <stdio.h>
  11. #include <tchar.h>
  12.  
  13. // TODO: reference additional headers your program requires here

3. stdafx.cpp

  1. // stdafx.cpp : source file that includes just the standard includes
  2. // FindInPartiallySortedMatrix.pch will be the pre-compiled header
  3. // stdafx.obj will contain the pre-compiled type information
  4.  
  5. #include "stdafx.h"
  6.  
  7. // TODO: reference any additional headers you need in STDAFX.H
  8. // and not in this file

4. FindInPartiallySortedMatrix.cpp

  1. // FindInPartiallySortedMatrix.cpp : Defines the entry point for the console application.
  2. //
  3.  
  4. // 《剑指Offer——名企面试官精讲典型编程题》代码
  5. // 著作权所有者:何海涛
  6.  
  7. #include "stdafx.h"
  8.  
  9. // 二维数组matrix中,每一行都从左到右递增排序,
  10. // 每一列都从上到下递增排序
  11. bool Find(int* matrix, int rows, int columns, int number)
  12. {
  13. bool found = false;
  14.  
  15. if(matrix != NULL && rows > && columns > )
  16. {
  17. int row = ;
  18. int column = columns - ;
  19. while(row < rows && column >=)
  20. {
  21. if(matrix[row * columns + column] == number)
  22. {
  23. found = true;
  24. break;
  25. }
  26. else if(matrix[row * columns + column] > number)
  27. -- column;
  28. else
  29. ++ row;
  30. }
  31. }
  32.  
  33. return found;
  34. }
  35.  
  36. // ====================测试代码====================
  37. void Test(char* testName, int* matrix, int rows, int columns, int number, bool expected)
  38. {
  39. if(testName != NULL)
  40. printf("%s begins: ", testName);
  41.  
  42. bool result = Find(matrix, rows, columns, number);
  43. if(result == expected)
  44. printf("Passed.\n");
  45. else
  46. printf("Failed.\n");
  47. }
  48.  
  49. // 1 2 8 9
  50. // 2 4 9 12
  51. // 4 7 10 13
  52. // 6 8 11 15
  53. // 要查找的数在数组中
  54. void Test1()
  55. {
  56. int matrix[][] = {{, , , }, {, , , }, {, , , }, {, , , }};
  57. Test("Test1", (int*)matrix, , , , true);
  58. }
  59.  
  60. // 1 2 8 9
  61. // 2 4 9 12
  62. // 4 7 10 13
  63. // 6 8 11 15
  64. // 要查找的数不在数组中
  65. void Test2()
  66. {
  67. int matrix[][] = {{, , , }, {, , , }, {, , , }, {, , , }};
  68. Test("Test2", (int*)matrix, , , , false);
  69. }
  70.  
  71. // 1 2 8 9
  72. // 2 4 9 12
  73. // 4 7 10 13
  74. // 6 8 11 15
  75. // 要查找的数是数组中最小的数字
  76. void Test3()
  77. {
  78. int matrix[][] = {{, , , }, {, , , }, {, , , }, {, , , }};
  79. Test("Test3", (int*)matrix, , , , true);
  80. }
  81.  
  82. // 1 2 8 9
  83. // 2 4 9 12
  84. // 4 7 10 13
  85. // 6 8 11 15
  86. // 要查找的数是数组中最大的数字
  87. void Test4()
  88. {
  89. int matrix[][] = {{, , , }, {, , , }, {, , , }, {, , , }};
  90. Test("Test4", (int*)matrix, , , , true);
  91. }
  92.  
  93. // 1 2 8 9
  94. // 2 4 9 12
  95. // 4 7 10 13
  96. // 6 8 11 15
  97. // 要查找的数比数组中最小的数字还小
  98. void Test5()
  99. {
  100. int matrix[][] = {{, , , }, {, , , }, {, , , }, {, , , }};
  101. Test("Test5", (int*)matrix, , , , false);
  102. }
  103.  
  104. // 1 2 8 9
  105. // 2 4 9 12
  106. // 4 7 10 13
  107. // 6 8 11 15
  108. // 要查找的数比数组中最大的数字还大
  109. void Test6()
  110. {
  111. int matrix[][] = {{, , , }, {, , , }, {, , , }, {, , , }};
  112. Test("Test6", (int*)matrix, , , , false);
  113. }
  114.  
  115. // 鲁棒性测试,输入空指针
  116. void Test7()
  117. {
  118. Test("Test7", NULL, , , , false);
  119. }
  120.  
  121. int _tmain(int argc, _TCHAR* argv[])
  122. {
  123. Test1();
  124. Test2();
  125. Test3();
  126. Test4();
  127. Test5();
  128. Test6();
  129. Test7();
  130.  
  131. return ;
  132. }

5. 项目 03_FindInPartiallySortedMatrix 下载

百度网盘: 03_FindInPartiallySortedMatrix.zip

参考资料

[1]  何海涛. 剑指 Offer:名企面试官精讲典型编程题 [M]. 北京:电子工业出版社,2012. 38-41.

二维数组中的查找(C++和Python实现)的更多相关文章

  1. 剑指Offer面试题:2.二维数组中的查找

    一.题目:二维数组中的查找 题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数. ...

  2. 剑指Offer:面试题3——二维数组中的查找(java实现)

    问题描述:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数. 思路:取数组中的元素与 ...

  3. 【面试题003】c数组做为参数退化的问题,二维数组中的查找

    [面试题003]c数组做为参数退化的问题,二维数组中的查找  一,c数组做为参数退化的问题 1.c/c++没有记录数组的大小,因此用指针访问数组中的元素的时候,我们要确保没有超过数组的边界, 通过下面 ...

  4. 九度OJ 题目1384:二维数组中的查找

    /********************************* * 日期:2013-10-11 * 作者:SJF0115 * 题号: 九度OJ 题目1384:二维数组中的查找 * 来源:http ...

  5. 《剑指Offer》面试题-二维数组中的查找

    题目1384:二维数组中的查找 时间限制:1 秒 内存限制:32 兆 特殊判题:否 提交:7318 解决:1418 题目描述: 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到 ...

  6. 《剑指offer》— JavaScript(1)二维数组中的查找

    二维数组中的查找 题目描述 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数. ** ...

  7. 剑指offfer:二维数组中的查找

    题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完成这样一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数. 例如: 1    2  ...

  8. C#版 - 小红书后台开发面试题: 二维数组中的查找

    二维数组中的查找 热度指数:24274 时间限制:1秒 空间限制:32768K 本题知识点: 查找 ​ 在线提交网址: http://www.nowcoder.com/practice/abc3fe2 ...

  9. 二维数组中的查找问题--剑指offer面试题3

    题目:在一个二维数组中,对每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数. // 二维数组中的查找 ...

  10. 《剑指offer》 二维数组中的查找

    本题目是<剑指offer>中的题目 二维数组中的查找 题目: 在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完成一个 ...

随机推荐

  1. python安装方法

    1.下载Python安装包 2.配置环境变量 path=%path%;C:\Python27 3.安装pip 默认已安装 4.配置pip环境变量 path=%path%;C:\Python27\Scr ...

  2. linux curl post/put请求

    案列: -X: 请求方式 --header: 请求header -d: 请求的数据 最后跟上请求的地址 curl -X PUT --header 'Content-Type: application/ ...

  3. Math.round、Math.floor、Math.ceil 区别

    1.Math.round() 按照四舍五入的方式返回值 例如:Math.round(9.5)=10    Math.round(9.4)=9 2.Math.floor()返回最小整数 例如:Math. ...

  4. ffmpeg intro - pull and push

    ffmpeg -i rtmp://rtmp.test.com/live/livestream -c:v copy -c:a copy -f flv rtmp://172.31.11.53/myhls/ ...

  5. (转)Uri详解之——Uri结构与代码提取

    前言:依然没有前言…… 相关博客:1.<Uri详解之——Uri结构与代码提取>2.<Uri详解之二——通过自定义Uri外部启动APP与Notification启动> 上几篇给大 ...

  6. 通过overflow: scroll;来实现部分区域的滚动

    在移动端中,我们希望元素的滚动,可以通过一些插件的使用来实现滚动,当然也可以自己来实现. 比如:对于某一个区域,我们可以限制好高度之后,设定:overflow-y: scroll; 这样,就可以实现滚 ...

  7. Eclipse更改颜色主题

    通过在线安装的方式 Help -> Install New Software Work with: 输入 http://eclipse-color-theme.github.com/update ...

  8. Firebird 有用的list函数

    语法: LIST ([ALL | DISTINCT] expression [, separator]) 示例: select list(u.code, ';') from m_user u 结果:查 ...

  9. [转]真正了解CSS3背景下的@font face规则

    本文转自:http://www.zhangxinxu.com/wordpress/2017/03/css3-font-face-src-local/ by zhangxinxu from http:/ ...

  10. asp get与post获取的区别

    1.HTTP请求格式: <request line> <headers> <blank line> [<request-body>] 在HTTP请求中, ...