Skip to content

Commit 0a41ea9

Browse files
committed
feat: 0074 Search a 2D Matrix
1 parent e891be5 commit 0a41ea9

File tree

2 files changed

+34
-3
lines changed

2 files changed

+34
-3
lines changed

Diff for: Leetcode/0074.Search-a-2D-Matrix/README.md

+33-2
Original file line numberDiff line numberDiff line change
@@ -72,8 +72,8 @@ seo:
7272

7373
## Big O
7474

75-
* 時間複雜 : ``
76-
* 空間複雜 : ``
75+
* 時間複雜 : `O(log⁡mn)` 其中 m 和 n 分別是矩陣的行數和列數
76+
* 空間複雜 : `O(1)`
7777

7878
## 來源
7979
* https://leetcode.com/problems/search-a-2d-matrix/description/
@@ -83,6 +83,37 @@ seo:
8383
https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0074.Search-a-2D-Matrix/main.go
8484

8585
```go
86+
package searcha2dmatrix
87+
88+
// 時間複雜 O(logmn), 空間複雜 O(1)
89+
func searchMatrix(matrix [][]int, target int) bool {
90+
m := len(matrix)
91+
if m <= 0 {
92+
return false
93+
}
94+
n := len(matrix[0])
95+
96+
left, right := 0, m*n-1
97+
for left <= right {
98+
mid := int(uint(right+left) >> 1) //left + (right-left)/2
99+
val := getMatrix(matrix, mid)
100+
if val == target {
101+
return true
102+
} else if val < target {
103+
left = mid + 1
104+
} else {
105+
right = mid - 1
106+
}
107+
}
108+
return false
109+
}
110+
111+
// 將 mxn的二維陣列 映射成一維陣列
112+
func getMatrix(matrix [][]int, index int) int {
113+
n := len(matrix[0])
114+
i, j := index/n, index%n
115+
return matrix[i][j]
116+
}
86117

87118
```
88119

Diff for: Leetcode/0074.Search-a-2D-Matrix/main.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
package searcha2dmatrix
22

3-
// 時間複雜 O(), 空間複雜 O()
3+
// 時間複雜 O(logmn), 空間複雜 O(1)
44
func searchMatrix(matrix [][]int, target int) bool {
55
m := len(matrix)
66
if m <= 0 {

0 commit comments

Comments
 (0)