ノートタイトルleetcodeブラシ(Golang) - 74は、2次元マトリックスを検索します。

74 2Dマトリックスを検索

効率的なアルゴリズムを書くMXN行列内の値を検索しています。この行列は、次のプロパティがあります。

各列の整数を左から右にソートされます。
各行の最初の整数は、前の行の最後の整数よりも大きいです。
例1:

入力:
行列= [
[1、3、5、7]、
[10、11、16、20]、
[23、30、34、50]
]
= 3ターゲット
出力:真
例2:

INPUT:
マトリックス= [
[1 ,. 3 ,. 5 ,. 7]、
[10 ,. 11、16、20]、
[23 34、30である50]、である
]
ターゲットは= 13である
falseに:出力
解決アイデア

func searchMatrix(matrix [][]int, target int) bool {
	if len(matrix) == 0 {
		return false
	}
	rows, cols := len(matrix), len(matrix[0])
	r := 0
	c := cols - 1
	for r < rows && c >= 0 {
		if matrix[r][c] == target {
			return true
		} else if matrix[r][c] > target {
			c--
		} else {
			r++
		}
	}
	return false   
}
发布了65 篇原创文章 · 获赞 0 · 访问量 359

おすすめ

転載: blog.csdn.net/weixin_44555304/article/details/104286136