-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path240. Search a 2D Matrix II.cpp
35 lines (33 loc) · 1.05 KB
/
240. Search a 2D Matrix II.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Binary Search Solution
// class Solution {
// public:
// bool binarySearch(vector<int>& v, int target,int from,int to){
// if(from>to) return false;
// int mid = from + (to-from)/2;
// if(v[mid]==target) return true;
// if(v[mid]> target) return binarySearch(v,target,from,mid-1);
// return binarySearch(v,target,mid+1,to);
// }
// bool searchMatrix(vector<vector<int>>& matrix, int target) {
// int n=matrix.size();
// int m=matrix[0].size();
// for(vector<int>& v:matrix){
// if(v[0]<=target && v[m-1]>=target && binarySearch(v,target,0,m-1)) return true;
// }
// return false;
// }
// };
// Iterative Solution
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int i = matrix.size()-1;
int j=0;
while(i>=0 && j<matrix[0].size()){
if(matrix[i][j]>target) i--;
else if (matrix[i][j]<target) j++;
else return true;
}
return false;
}
};