题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
C++11实现
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
bool Find(vector<vector<int> > array,int target)
{
    int rowCount = array.size();
    int colCount = array[0].size();
    int i,j;
    for(i=rowCount-1,j=0; i>=0&&j<colCount;)
    {
        if(target == array[i][j])
            return true;
        if(target < array[i][j])
        {
            i--;
            continue;
        }
        if(target > array[i][j])
        {
            j++;
            continue;
        }
    }
    return false;
}
int main()
{
    int k = 0;
    string sval;
    vector<int> sVec;
    vector<vector<int>> pVec;
    for(int j = 0; j < 5; ++j)
    {
        for(int i = k; i < 10+k; ++i)
            sVec.push_back(i);
        k++;
        cout << "Child vector "<< sVec.size() << endl;
        for(vector<int>::iterator itor = sVec.begin(); itor != sVec.end(); itor++)
            cout << *itor << endl;
        pVec.push_back(sVec);
        sVec.clear();
    }
    cout << "Parent vector "<< pVec.size() << endl;
    do
    {
        cout <<"Please input the check integer" << endl ;
        cin >> sval;
        if(!Find(pVec,stoi(sval)))
            cout << "Not find the integer data "<< endl;
        else
            cout << "Find the integer data "<< endl;
    }
    while(1);
    return 0;
}思路
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|  1   |  2   |  3   |  4   |  5   |  6   |  7   |  8   |  9   |  10  |
|  2   |  3   |  4   |  5   |  6   |  7   |  8   |  9   |  10  |  11  |
|  3   |  4   |  5   |  6   |  7   |  8   |  9   |  10  |  11  |  12  |
|  4   |  5   |  6   |  7   |  8   |  9   |  10  |  11  |  12  |  13  |
先从最后一行第一个数字4开始检索i=rowCount-1,j=0,假设为m与目标值n比对。
1. m < n,自然行数不用增加,增加列数向右查询
2. m > n, 自然行数向上查询
3. m == n,已找到,退出
这个题目没啥技术含量哈
来源:https://www.cnblogs.com/yiyi20120822/p/11327531.html