1. [Two-dimensional ordered array search]

In a two-dimensional array, each row is sorted in increasing order from left to right, and each column is sorted in increasing order from top to bottom. Please complete a function, input such a two-dimensional array and an integer, and determine whether the array contains the integer.

 

The solution must be to use the O(n) level. If it is O(N^2), then it is still brute force. In this way, the nature of the title is not used at all ==== "two-dimensional ordered array, so let's honestly think about the O(N) algorithm!

 

That is, there is an array that satisfies the following laws:

	 ------>
	|
	|
	|
How to quickly find one of the elements?

 

 

There is a problem: the problem is coming, if you start from (0,0), then the problem must be extremely disgusting, because you don't know whether to go down or to the right next time. . . Because [both directions are increasing]

Discovering the problem: At this time, we learned that the problem is that [starting from (0,0) will increase whether it goes right or down. ] Then is there a point that makes [increase in one direction and decrease in one direction]?
Solve the problem: Using the (0,n-1) point or (n-1,0) point, you will find that one direction is increasing and the other is decreasing. If the value is small, search in the increasing direction, and if the value is large, decrease in the decreasing direction. At this time, the code is very easy to write.

 

Code:

 

    bool Find(int target, vector<vector<int> > array) {
        int row = array.size();
        int col = array[0].size();
        for (int i = 0,j = col - 1; i < row && j >= 0;)
        {
            if (array[i][j] == target)
            {
                return true;
            }
            if (array[i][j] < target)
            {
                ++i;
            }
            else
            {
                --j;
            }
        }
        return false;
    }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325528513&siteId=291194637