33.寻找目标值 - 二维数组

这是第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
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值