Find in 3-two-D arrays

Source: Internet
Author: User

Problem Description: In a two-dimensional array, each row is ordered in ascending order from left to right, and each column is sorted in ascending order from top to bottom. Complete a function, enter a two-dimensional array and an integer to determine if the array contains the integer.

    • First, select the number in the upper-right corner of the array. If the number is equal to the number you are looking for, the lookup process ends, and if the number is greater than the number you are looking for, the column containing the number is excluded, and if the number is less than the number you are looking for, the row containing the number is excluded. That is, if the number you are looking for is not in the upper-right corner of the array, each time you exclude a row or column from the array's look-up, each step narrows the search until you find the number you are looking for, or the lookup range is empty.
bool Find(int *matrix, int rows, int cols, int number){    bool found = false;    if(matrix != nullptr && rows>0 && cols>0){        int row = 0;        int col = cols-1;        while(row<rows && col>=0){            if(matrix[row*cols+col] == number){                found = true;                break;            }            else if(matrix[row*cols+col] < number)                ++row;            else                --col;        }    }    return found;}

Find in 3-two-D arrays

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.