Skip to content

Instantly share code, notes, and snippets.

@coffeewasmyidea
Created August 7, 2023 15:30
Show Gist options
  • Save coffeewasmyidea/b135a8be3b06dc0f65c3556962108e4a to your computer and use it in GitHub Desktop.
Save coffeewasmyidea/b135a8be3b06dc0f65c3556962108e4a to your computer and use it in GitHub Desktop.
package main
import "fmt"
func searchMatrix(matrix [][]int, target int) bool {
if len(matrix) == 0 {
return false
}
m, n := len(matrix), len(matrix[0])
left, right := 0, m*n-1
for left <= right {
mid := left + (right-left)/2
mid_row := mid / n
mid_col := mid - mid_row*n
if matrix[mid_row][mid_col] == target {
return true
} else if matrix[mid_row][mid_col] < target {
left = mid + 1
} else {
right = mid - 1
}
}
return false
}
func main() {
matrix := [][]int{
{1, 3, 5, 7},
{10, 11, 16, 20},
{23, 30, 34, 50},
}
target := 3
found := searchMatrix(matrix, target)
if found {
fmt.Printf("Target %d found.\n", target)
} else {
fmt.Printf("Target %d not found.\n", target)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment