search for a number in a two-dimensional ordered array (presence of no, number of occurrences)Problem Description
Write an efficient algorithm to search for values in the MXN matrix, returning the number of occurrences of this value.
This matrix has the following characteristics:
The integers in each row are sorted from left to right.
The integers of each column are sorted from top to bottom.
There are no duplicate integers in each row or column.
Sample Example
Consider the following matrices:
[
[1, 3, 5, 7],[2, 4, 7, 8],[3, 5, 9, 10]
]
Give target = 3, return 2
Implementation Ideas
Since each row of the array is ordered from left to right and each column is ordered from top to bottom, you can consider starting the search from the upper-right corner of the two-dimensional array. First, the relationship between the upper right and the find target is judged, and if the target is smaller than the upper-right element, the last column is not searched, and if the target is greater than the upper-right element, the first row is not searched.
The search path is as follows:
If the question asks if the target value exists, when the first target value is searched, the search function returns to True, and if the topic asks for the number of occurrences, continue searching.
Code Implementation
classSolution { Public:/** * @param matrix:a List of lists of integers * @paramTarget: anintegerYou want to searchinchMatrix * @return: anintegerIndicate the total occurrence ofTarget inchThe given matrix */intSearchmatrix (vector<vector<int> > &matrix,int Target) { //WriteYour code hereif(Matrix.size() ==0)return 0;intcols = matrix[0].size();introws = Matrix.size();int Count=0;introw =0;intCol = cols-1; while(Row<rows && col>=0) {if(Matrix[row][col] = =Target) {Count++; row++; }Else if(Matrix[row][col] <Target) {row++; }Elsecol--; }return Count; }};
Reprint Please specify Source: http://www.cnblogs.com/scut-linmaojiang/p/5146435.html
Search for a number in a two-dimensional ordered array (presence of no, number of occurrences)