这是第33篇算法,力扣链接
m
*n
的二维数组plants
记录了园林景观的植物排布情况,具有以下特性:
- 每行中,每棵植物的右侧相邻植物不矮于该植物;
- 每列中,每棵植物的下侧相邻植物不矮于该植物。
请判断
plants
中是否存在目标高度值target
。示例 1:
输入:plants = [[2,3,6,8],[4,5,8,9],[5,9,10,12]], target = 8 输出:true
这道题其实还是二维数组搜索,与 搜索二维数组 是一个题其实,首先暴力搜索(Z字搜索)逻辑如下:
func findTargetIn2DPlants(plants [][]int, target int) bool {
if len(plants) == 0 {
return false
}
width, wMax, high := 0, len(plants[0]), len(plants)-1
for width < wMax && high >= 0 {
if plants[high][width] == target {
return true
}
if plants[high][width] < target {
width++
} else {
high--
}
}
return false
}
与上道题同理,其实还有逐行二分查找:
func findTargetIn2DPlants(plants [][]int, target int) bool {
if len(plants) == 0 {
return false
}
for _, plant := range plants {
if len(plant) == 0 || target > plant[len(plant)-1] {
continue
}
if target < plant[0] {
return false
}
left, right := 0, len(plant)-1
for left <= right {
mid := (left + right) / 2
if plant[mid] == target {
return true
} else if plant[mid] < target {
left = mid + 1
} else {
right = mid - 1
}
}
}
return false
}