11.6 Given the m*n matrix, each row and column is sorted in ascending order, please write code to find out an element.
Similar to leetcode:search a 2D Matrix but unlike the one in Leetcode, the first element of the next line is not necessarily greater than the last element in the previous row. So using binary search is a bit of a hassle.
Solution One: By observing we know:
If the beginning of the column is greater than X, then x is on the left side of the column;
If the end of the column is less than x, then x is on the right side of the column;
If the beginning of the line is less than x, then x is above the row;
If the end of the line is less than x, then x is below the row
We can start the search from anywhere, but let's start with the starting element of the column.
We need to start with the largest column and then move to the left, which means that the first element to compare is array[0][c-1], where C is the number of columns.
C + + Implementation code:
#include <iostream>#include<vector>using namespacestd;BOOLFINDELEMEMT (vector<vector<int> > &matrix,inttarget) { if(Matrix.empty () | | matrix[0].empty ())return false; intm=matrix.size (); intn=matrix[0].size (); introw=0; intcol=n-1; while(row<m&&col>=0) { if(matrix[row][col]==target)return true; if(matrix[row][col]<target) Row++; ElseCol--; } return false;}intmain () {vector<vector<int> > vec={{ the, -, +, -},{ -, *, the, the},{ -, -, the, the},{ +, the, -, -}}; cout<<FINDELEMEMT (VEC, -) <<Endl;}
careercup-Sorting and finding 11.6