-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path74 Search a 2D Matrix.java
68 lines (67 loc) · 2.22 KB
/
74 Search a 2D Matrix.java
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
57
58
59
60
61
62
63
64
65
66
67
68
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
//arrays are sorted
for(int i=0; i<matrix.length; i++){
if(matrix[i].length == 1){
if(target == matrix[i][0]){
return true;
}
else{
//continue
}
}
else if(matrix[i].length == 2){
int high = matrix[i][1];
int low = matrix[i][0];
if(target == high || target == low){
return true;
}
else{
//do nothing
}
}
else{
int first = matrix[i][0];
int last = matrix[i][matrix[i].length-1];
int mid = matrix[i][(matrix[i].length-1)/2];
int current = 0; //keep first by default
if(target == first || target==last||target==mid){
return true;
}
else if(target > last){
//skip
}
else if(target > mid){
// check the array, has to be between mid and last
current = ((matrix[i].length-1)/2)+1;
while(current < (matrix[i].length-1) ){
if(matrix[i][current] == target){
return true;
}
else{
current++;
}
}
break;//gone thry and failed
}
else if(target> first){
//check array, has to be between first and mid
current = 1; //
while( current < ((matrix[i].length-1)/2) ){
if(matrix[i][current] == target){
return true;
}
else{
current++;
}
}
}
else{
//error!
}
}
}
//default
return false;
}
}