Find a number in increments array

Find a number in increments arrayPeople face questions shivering
.
.
.

Find a number in increments arrayWe look to the subject
in a two-dimensional array, each row from left to right in order of increasing operation. Each column sorted in ascending order from top to bottom. Completion code, the input of such a two-dimensional array and an integer, it is determined whether the array contains the integer

Find a number in increments arrayHow to solve Le? ? ?
Analysis: Find a number in increments arrayIf this is a two-dimensional array, in order to solve the problem entirely possible to traverse the array again, but for efficiency, we need to reduce the time complexity, in order to traverse the fewest numbers, we need to separate the rows and columns. So, we will find an array from a digital judge, however, casually looking for a number, will only make the problem becomes complicated with, for example, to find a 10 left and top edges than 10 hours, and below and to the right than the 10 big, so we can only find some specific points, for example, upper-right, lower left, there is only one way to make your choice. a [row] [col], we take 9 For example, if the numbers are looking for more than nine, just row ++; if the numbers look smaller than 9, just col--; until finally find the required number.
Find a number in increments arrayLook at the code

#include<iostream>
using namespace std;

bool find(int *arr, int row, int col, int n)
{
    bool flag = false;//标记
    if (arr != nullptr&&row > 0 && col > 0)//判断数组是否存在
    {
        int _row = 0;
        int _col = col - 1;
        while (_col>0&&_row<row)
        {
            if (arr[_row*col + _col] > n)
            {
                _col--;
            }
            else if (arr[_row*col + _col] < n)
            {
                _row++;
            }
            else
            {
                flag = true;
                return flag;
            }
        }
    }
    return flag;
}
int main()
{
    int arr[4][4] = { { 1, 2, 8, 9 }, { 2, 4, 9, 12 }, { 4, 7, 10, 13 }, { 6, 8, 11, 15 } };
    bool ret=find((int *)arr, 4, 4, 7);//
    cout << boolalpha << ret<<endl;//boolapha使返回值变成true输出
    return 0;
}

Guess you like

Origin blog.51cto.com/14233078/2437860