《剑指offer》JZ1(001) 二维数组中的查找
题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
题目分析 – 法一
在其中寻找 5 是否存在。过程如下:
- 从右上角开始遍历
- 当前元素小于目标元素(3 < 5),根据数组特点,当前行中最大元素也小于目标元素,因此进入下一行
- 当前元素大于目标元素(6 > 5),根据数组特点,行数不变,尝试向前一列查找
找到 5
/** 方法1 适用于 两种情况( 牛客网要求的是 同时符合 情况1 和 情况2 )
*
* 情况1
* vector<vector<int>> _array1 = {
* {1, 2, 3},
* {4, 5, 6},
* {7, 8, 9}};
*
* 情况2
* vector<vector<int>> _array2 = {
* {1, 2, 8, 9},
* {2, 4, 9, 12},
* {4, 7, 10, 13},
* {6, 8, 11, 15}};
*/
题目分析 – 法二
二维数组中,对满足条件的一维数组使用二分查找,加速某一行的查找
/** 方法2 适用于 两种情况( 牛客网要求的是 同时符合 情况1 和 情况2 )
*
* 情况1
* vector<vector<int>> _array1 = {
* {1, 2, 3},
* {4, 5, 6},
* {7, 8, 9}};
*
* 情况2
* vector<vector<int>> _array2 = {
* {1, 2, 8, 9},
* {2, 4, 9, 12},
* {4, 7, 10, 13},
* {6, 8, 11, 15}};
*/
code
#include <iostream>
#include <vector>
using namespace std;
//#define SOLUTION
#ifdef SOLUTION
class Solution
{
public:
bool Find(int target, vector<vector<int>> &array)
{
const int len_first = array.size(); //一维数组的个数
const int len_second = array[0].size(); //一维数组的长度
if (0 == len_first || 0 == len_second)
{
return false;
}
int fir = 0;
int sec = len_second - 1;
while (fir < len_first && sec >= 0)
{
if (array[fir][sec] == target)
return true;
else if (array[fir][sec] > target)
--sec;
else
++fir;
}
return false;
}
};
#else
class Solution
{
public:
bool Find(int target, vector<vector<int>> &array)
{
const int len_first = array.size(); //一维数组的个数
const int len_second = array[0].size(); //一维数组的长度
if (0 == len_first || 0 == len_second)
{
return false;
}
int fir = 0;
int sec = len_second - 1;
while (fir < len_first && sec >= 0)
{
if (array[fir][sec] == target)
return true;
else if ((array[fir][sec] > target) && (array[fir][0] <= target))
{
if (true == BinarySearch(array, fir, 0, sec - 1, target))
return true;
else
++fir;
}
else if ( array[fir][0] > target)
{
break;
}
else
++fir;
}
return false;
}
bool BinarySearch(vector<vector<int>> &_array, int row, int left, int right, int target)
{
int mid = (left + right) / 2;
while (left <= right)
{
mid = (left + right) / 2;
if (target == _array[row][mid])
return true;
else if (target > _array[row][mid])
left = mid + 1;
else if (target < _array[row][mid])
right = mid - 1;
}
return false;
}
};
#endif
int main()
{
Solution s1;
vector<vector<int>> _array1 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
cout << s1.Find(5, _array1) << endl;
vector<vector<int>> _array2 = {
{1, 2, 8, 9},
{2, 4, 9, 12},
{4, 7, 10, 13},
{6, 8, 11, 15}};
cout << s1.Find(7, _array2) << endl;
return 0;
}
// [root@lwh TheSwordRefersToOffer]# g++ test.cpp -std=c++11
// [root@lwh TheSwordRefersToOffer]# ./a.out
// 1
// [root@lwh TheSwordRefersToOffer]#