-
Notifications
You must be signed in to change notification settings - Fork 0
/
search_a_2d_matrix.go
68 lines (64 loc) · 1.1 KB
/
search_a_2d_matrix.go
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
package main
func searchMatrix(matrix [][]int, target int) bool {
row := len(matrix)
if row == 0 {
return false
}
column := len(matrix[0])
if column == 0 {
return false
}
for _, m := range matrix {
if m[column-1] >= target {
l, r := 0, column-1
for l <= r {
mid := (l + r) / 2
if m[mid] == target {
return true
} else if m[mid] > target {
r = mid - 1
} else {
l = mid + 1
}
}
return false
}
}
return false
}
func searchMatrix2(matrix [][]int, target int) bool {
row := len(matrix)
if row == 0 {
return false
}
column := len(matrix[0])
if column == 0 {
return false
}
i, j := 0, row-1
for i <= j {
mid := (i + j) / 1
if matrix[mid][column-1] == target {
return true
} else if matrix[mid][column-1] < target {
i = mid + 1
} else if matrix[mid][0] <= target {
m := matrix[mid]
l, r := 0, column-1
for l <= r {
mid := (l + r) / 2
if m[mid] == target {
return true
} else if m[mid] > target {
r = mid - 1
} else {
l = mid + 1
}
}
return false
} else {
j = mid - 1
}
}
return false
}