The sword refers to offer-3. Find in a two-D array

Source: Internet
Author: User

0 topics

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 this integer.

1 analysis

The first thing to think about an orderly array is a binary lookup.

This two-dimensional array is characterized by a point in the array that is larger than the number at that point, right and bottom. Both the left and the top are smaller than the number.

But at the same time to judge two of the same dimension, more trouble.

So first judge two different dimensions. That is to say, judge a point to the right and bottom, or to the left and above. Then one of the directions is large and the other direction is small.

To judge the right and the following as an example:

Go to the point on the left, first, if the target number is larger than the current point, then move down, if it is smaller than the target point, then move to the right, this time the point of the bottom is a selection of areas, sit down is the filtered area

BOOL Find (int target, vector<vector<int>> array) {    size_t rows = array.size ();    if (rows = = 0)    {        return false;    }    size_t cols = Array[0].size ();    if (cols = = 0)    {        return false;    }    Col, and Row is the point on the right of the    int col = cols-1;    int row = 0;    The point moves to the left, so col>=0, row < rows while    (col >= 0 && row < rows)    {        if (target = = Array[ro W][col])        {            return true;        }        else if (target < Array[row][col])//greater than, move down        {            --col;        }        else if (Target > Array[row][col])//less than, move to left        {            ++row;        }    }    return false;}


The sword refers to offer-3. Find in a two-D array

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.