If ❤️ my article is helpful, welcome to like, follow. This is the biggest encouragement for me to continue my technical creation.

PS: The source code is at the end

The source code

package main

import "fmt"

Are values in a two-dimensional array sorted in ascending order from left to right, and ascending order from top to bottom for each column? Complete a function that takes such a two-dimensional array and an integer and determines whether the integer is in the array. ,5,8,12,19,4,7,11,15 {{1}, {2}, {10,6,9,16,22}, {20,13,14,17,24}, 18,21,23,26,30} {and} a given target = 7, return true. Given target = 3, return false. * /


/** Return true if you find an element that is equal to the target value. Otherwise return false. * /
func isExistV1(matrix [][]int, target int) bool {
	for i:=0; i<len(matrix); i++ {
		for j:=0; j<len(matrix[i]); j++ {
			if matrix[i][j] == target{
				return true}}}return false
}

func isExistV2(matrix [][]int, target int) bool {
	i:=0 	// matrix[0] {1,2,8,9}
	j:=0	// matrix[0][0
	for i<len(matrix){
		if j<len(matrix[i]){
			if target<matrix[i][j]{
				i++  // Since each row is sorted in ascending order from left to right, target < the first element in the row, meaning it is also smaller than all elements in the row
				j=0
			}else if target>matrix[i][j]{
				j++ // target > the first element in the line, continue to compare the next element
			}else if target==matrix[i][j]{
				return true}}else{
			return false	// Out of array returns false}}return false	// beyond matrix returns false
}

func main(a)  {
	temArr := [][]int{{1.4.7.11.15},
		{2.5.8.12.19},
		{10.6.9.16.22},
		{20.13.14.17.24},
		{18.21.23.26.30},
	}


	ret1 := isExistV1(temArr, 7)
	fmt.Println("check 7 is exist:", ret1)

	ret2 := isExistV1(temArr, 3)
	fmt.Println("check 3 is exist:", ret2)
}

Copy the code