Search a 2D MatrixTotal accepted:40009 Total submissions:127082my submissions QuestionSolution
Write an efficient algorithm, searches for a value in a m x n Matrix. This matrix has the following properties:
- Integers in each row is sorted from the left to the right.
- The first integer of each row was greater than the last integer of the previous row.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [Ten, One,], [23, 30, 34, 50]]
Given target = 3 , return true .
Hide TagsArray Binary SearchHas you met this question in a real interview? Yes No
Discuss
#include <iostream> #include <vector>using namespace std;/* The problem is to find a specified number from top to bottom in an orderly array, incrementing from left to right, So from right to left, each time compared to the topmost number */bool Searchmatrix (vector<vector<int>>& matrix, int target) {int x=matrix.size ( ); int y=matrix[0].size (); for (int j=y-1;j>=0;j--) {if (Target==matrix[0][j]) return true;if (Target>matrix[0][j] {for (int i=1;i<=x-1;i++) if (Target==matrix[i][j]) return true;}} return false;} int main () {vector<vector<int> > Vec0;vector<int> vec;vec.push_back (1); Vec0.push_back (VEC); Vec.clear (); Vec.push_back (3); Vec0.push_back (VEC); Cout<<searchmatrix (vec0,3) <<endl;}
leetcode_74 title--search a 2D Matrix (array lookup)