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