Files
LeetCode-Go/leetcode/0240.Search-a-2D-Matrix-II/240. Search a 2D Matrix II.go
2020-08-07 17:06:53 +08:00

41 lines
795 B
Go

package leetcode
// 解法一 模拟,时间复杂度 O(m+n)
func searchMatrix240(matrix [][]int, target int) bool {
if len(matrix) == 0 {
return false
}
row, col := 0, len(matrix[0])-1
for col >= 0 && row <= len(matrix)-1 {
if target == matrix[row][col] {
return true
} else if target > matrix[row][col] {
row++
} else {
col--
}
}
return false
}
// 解法二 二分搜索,时间复杂度 O(n log n)
func searchMatrix2401(matrix [][]int, target int) bool {
if len(matrix) == 0 {
return false
}
for _, row := range matrix {
low, high := 0, len(matrix[0])-1
for low <= high {
mid := low + (high-low)>>1
if row[mid] > target {
high = mid - 1
} else if row[mid] < target {
low = mid + 1
} else {
return true
}
}
}
return false
}