Skip to content

Commit

Permalink
go implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
Azureki committed May 20, 2019
1 parent 0618e64 commit 1132c18
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
14 changes: 14 additions & 0 deletions 240. Search a 2D Matrix II/README.org
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#+TITLE: 240. Search a 2D Matrix II
x,y 方向都递增的二维数组中找一个数。在剑指 offer 上做过。
* 文件及解法说明
** [[./sample_20ms_submission.go][20ms 示例解法]]
别人的。时间复杂度 O(mlogn)。

** [[./search_a_2d_matrix_ii.go][我的解法]]
O(m+n)

** 递归
midx, midy := (top+right)/2, (left+right)/2
若 matrix[midx][midy]<target, target 不可能在左上。接下来搜索右上,左下,右下;
若 matrix[midx][midy]>target, target 不可能在右下。

27 changes: 27 additions & 0 deletions 240. Search a 2D Matrix II/sample_20ms_submission.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
func searchMatrix(matrix [][]int, target int) bool {
for i := 0; i < len(matrix); i++ {
if binsearch(matrix[i], target) {
return true
}
}

return false
}

func binsearch(arr []int, target int) bool {
hi := len(arr) - 1
lo := 0

for lo <= hi {
mid := (lo + hi) / 2
if arr[mid] == target {
return true
} else if arr[mid] < target {
lo = mid + 1
} else {
hi = mid - 1
}
}

return false
}
18 changes: 18 additions & 0 deletions 240. Search a 2D Matrix II/search_a_2d_matrix_ii.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package leetcode

func searchMatrix(matrix [][]int, target int) bool {
if len(matrix) == 0 {
return false
}
x, y := 0, len(matrix[0])-1
for x < len(matrix) && y >= 0 {
if matrix[x][y] > target {
y--
} else if matrix[x][y] < target {
x++
} else {
return true
}
}
return false
}

0 comments on commit 1132c18

Please sign in to comment.