Title 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.
Problem Solving Ideas:
This is a question that examines the comprehension and programming capabilities of a two-dimensional array.
The two-dimensional array is continuously stored in memory. Stores row elements from top to bottom in memory, stored from left to right in the same row.
Therefore, you can calculate the position of relative array header by line number and column number.
Since each row and column is ordered, we can compare the number to be looked up to the upper-right corner of the array.
Because each row increments from left to right, each column increments from top to bottom.
So looking for a number num, you can do this:
First, compare num to the upper right corner of the number.
If it is equal, it is returned directly to find the number.
If num < upper right corner number, the upper right corner of the column is excluded col--
If num > upper right corner number, the upper right corner of the row is excluded row++
With this idea, we can write the code.
In fact, you can also choose to compare the number in the lower left corner. The method is the same as the upper right corner number above.
Code implementation:
<span style= "FONT-SIZE:18PX;" >class Solution {Public:bool Find (vector<vector<int> > array, int target) {bool ans = false;int Row_len = a Rray.size ();//Gets the number of rows int col_len = Array[0].size ();//Gets the number of columns if (!array.empty () && row_len > 0 && Col_len ; 0) {int row = 0;//Subscript zero-based int col = col_len-1;//same subscript starting from zero while (Row < Row_len && col>= 0)//Note here Col >= 0, Do not omit the = sign {if (Array[row][col] = = target) {ans = true;break;} else if (Array[row][col] > target)--col;else++row;}} return ans;}; </span>
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Interview questions 03_ two-dimensional array find _ Jian refers to the offer series