-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsearch_a_2d_matrix.go
More file actions
50 lines (42 loc) · 955 Bytes
/
search_a_2d_matrix.go
File metadata and controls
50 lines (42 loc) · 955 Bytes
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
package leetcode
// Time complexity: O(log n + log m) where n and m are the Nr. of rows and cols in the matrix
// Space complxity: O(1)
func searchMatrix(matrix [][]int, target int) bool {
findRow := func(matrix [][]int, target int) int {
left, right := 0, len(matrix)-1
for left <= right {
mid := left + (right-left)/2
if matrix[mid][0] > target {
right = mid - 1
} else if matrix[mid][len(matrix[0])-1] < target {
left = mid + 1
} else {
return mid
}
}
return -1
}
findEl := func(arr []int, target int) int {
left, right := 0, len(arr)-1
for left <= right {
mid := left + (right-left)/2
if target < arr[mid] {
right = mid - 1
} else if target > arr[mid] {
left = mid + 1
} else {
return mid
}
}
return -1
}
rowIdx := findRow(matrix, target)
if rowIdx == -1 {
return false
}
elIdx := findEl(matrix[rowIdx], target)
if elIdx == -1 {
return false
}
return true
}