Golang Leetcode 240. Search a 2D Matrix II.go

时间:2022-06-19
本文章向大家介绍Golang Leetcode 240. Search a 2D Matrix II.go,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

版权声明:原创勿转 https://blog.csdn.net/anakinsun/article/details/89055025

思路

从矩阵右上角开始遍历,如果大于target,则列数减一,如果小于target,则行数加一

code

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