File tree Expand file tree Collapse file tree 2 files changed +34
-3
lines changed
Leetcode/0074.Search-a-2D-Matrix Expand file tree Collapse file tree 2 files changed +34
-3
lines changed Original file line number Diff line number Diff line change 7272
7373## Big O
7474
75- * 時間複雜 : ``
76- * 空間複雜 : ``
75+ * 時間複雜 : ` O(logmn) ` 其中 m 和 n 分別是矩陣的行數和列數
76+ * 空間複雜 : ` O(1) `
7777
7878## 來源
7979* https://leetcode.com/problems/search-a-2d-matrix/description/
8383https://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
Original file line number Diff line number Diff line change 11package searcha2dmatrix
22
3- // 時間複雜 O(), 空間複雜 O()
3+ // 時間複雜 O(logmn ), 空間複雜 O(1 )
44func searchMatrix (matrix [][]int , target int ) bool {
55 m := len (matrix )
66 if m <= 0 {
You can’t perform that action at this time.
0 commit comments