-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
59 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 不可能在右下。 | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |