剑指Offer-4:二维数组中的查找
来源:互联网 发布:中国股市周期 知乎 编辑:程序博客网 时间:2024/06/06 03:56
题目:
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
Example:
如下面的二维数组,每行、每列都递增排序。如果 查找数字7,则返回true;如果查找数字5,则返回false。
1 2 8 92 4 9 124 7 10 136 8 11 15
问题解析:
- 从左到右,从上到下递增。
链接:
剑指Offer(第2版):P44
思路标签:
数据结构:数组
寻找直观简单的规律。
解答:
1. C++
- 本题对于初始判断元素的位置选取有很大的关系,如果我们从二维数组的中间选取,那么需要分三种情况进行讨论,且对后续的情况不容易进行处理,难以找出规律。从左上角开始,依然还是无法减小问题的规模。
- 如果从右上角开始讨论,对于大于需要寻找的元素的情况,就去掉该列;对于小于需要寻找的元素的情况,就去掉该行。不断减小问题需要寻找的规模,直至寻找到指定的元素为止。
- 这里我们仅需将二维数组作为连续地址空间处理即可,当然也可以使用二维vector。
一维数组:
class Solution {public: bool Find(int* matrix, int rows, int columns, int number){ bool found = false; if (matrix != nullptr && 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; }};
二维vector:
class Solution {public: bool Find(int target, vector<vector<int> > array) { bool found = false; int rows = array.size(); int columns = array[0].size(); if (!array.empty()){ int row = 0; int column = columns - 1; while (row < rows && column >= 0){ if (array[row][column] == target){ found = true; break; } else if (array[row][column] > target) --column; else ++row; } } return found; }};
C++相关:
二维vector:
- http://blog.csdn.net/a819825294/article/details/52088732
阅读全文
0 0
- 剑指Offer-4:二维数组中的查找
- 剑指offer-->二维数组中的查找
- 剑指offer之二维数组中的查找
- 剑指offer:3-二维数组中的查找
- [剑指Offer]二维数组中的查找
- 【剑指offer】二维数组中的查找
- [剑指Offer]二维数组中的查找
- 剑指Offer:二维数组中的查找
- 【剑指offer】二维数组中的查找
- 剑指offer 1384 二维数组中的查找
- 剑指Offer之二维数组中的查找
- 剑指offer 03:二维数组中的查找
- 剑指offer(2) - 二维数组中的查找
- 剑指offer-二维数组中的查找
- 剑指offer-3 二维数组中的查找
- 剑指Offer之 - 二维数组中的查找
- 剑指offer 3 -二维数组中的查找
- 剑指offer之二维数组中的查找
- 第八周(1) 项目2
- I2S音频总线学习(三)S3C2440的I2S控制器
- session机制
- could not find java.dllError: Could not find Java SE Runtime Environment.
- [poj1556]:The Doors
- 剑指Offer-4:二维数组中的查找
- 第五周 项目3 数据结构实践——括号的匹配(栈)
- 谈一谈Go的结构体struct的使用方法
- 条件随机场(Conditinal random field)
- 第14周项目4- 英文单词的基数排序
- Cloudera Manager 安装 CDH5.x 心得
- 图形图像网络参考资料
- java 内存模型
- LayUi Upload组件 和 C# .Net asp