Files
leetcode/top-100-liked/21/21_test.go
T
2026-06-13 04:08:10 +10:00

47 lines
1.0 KiB
Go

package top100liked
// https://leetcode.cn/problems/search-a-2d-matrix-ii/?envType=study-plan-v2&envId=top-100-liked
import (
"fmt"
"testing"
)
func searchMatrix(matrix [][]int, target int) bool {
for i := range len(matrix) {
for j := range len(matrix[0]) {
if matrix[i][j] == target {
return true
}
if j == 0 && matrix[i][j] > target {
return false
}
if matrix[i][j] > target {
break
}
}
}
return false
}
// func searchMatrix(matrix [][]int, target int) bool {
// m, n := len(matrix), len(matrix[0])
// x, y := 0, n-1
// for x < m && y >= 0 {
// if matrix[x][y] == target {
// return true
// }
// if matrix[x][y] > target {
// y--
// } else {
// x++
// }
// }
// return false
// }
func TestS21(t *testing.T) {
fmt.Println(searchMatrix([][]int{{1, 4, 7, 11, 15}, {2, 5, 8, 12, 19}, {3, 6, 9, 16, 22}, {10, 13, 14, 17, 24}, {18, 21, 23, 26, 30}}, 5))
fmt.Println(searchMatrix([][]int{{1, 4, 7, 11, 15}, {2, 5, 8, 12, 19}, {3, 6, 9, 16, 22}, {10, 13, 14, 17, 24}, {18, 21, 23, 26, 30}}, 20))
}