-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSearch a 2D Matrix
56 lines (40 loc) · 876 Bytes
/
Search a 2D Matrix
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
bool searchMatrix(int** matrix, int matrixSize, int* matrixColSize, int target){
int col = *matrixColSize;
int row = matrixSize;
if(row*col == 1){
if(matrix[0][0] == target){
return true;
}else{
return false;
}
}
for(int i = 0; i < row; i++){
if(matrix[i][0] <= target && target <= matrix[i][col-1]){
int left = 0;
int right = col-1;
if((col == 1 ) && (matrix[i][col-1] == target)){
return true;
}
if((col == 2) && (matrix[i][0] == target || matrix[i][1] == target )){
return true;
}
while(left < right){
int mid = left + (right -left)/2;
if(matrix[i][mid] == target){
return true;
}
if(matrix[i][mid] > target ){
right = mid;
}else{
left = mid+1;
}
}
if(left == right){
if(matrix[i][left] == target){
return true;
}
}
}
}
return false;
}