1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
| package main
import "fmt"
func searchMatrix_0(matrix [][]int, target int) bool { rows, cols := len(matrix), len(matrix[0]) for row := 0; row < rows; row ++ { left, right := 0, cols - 1 for left <= right { mid := left + (right - left)/2 if matrix[row][mid] == target { return true } else if matrix[row][mid] < target { left = mid + 1 } else { right = mid - 1 } } }
return false }
func searchMatrix(matrix [][]int, target int) bool { rows, cols := len(matrix), len(matrix[0]) x, y := 0, cols - 1
for x < rows && y >= 0 { if matrix[x][y] == target { return true } else if matrix[x][y] > target { y -- } else { x ++ } } return false }
func main() { testCases := []struct { matrix [][]int target int expected bool }{ { matrix: [][]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}, }, target: 5, expected: true, }, { matrix: [][]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}, }, target: 20, expected: false, }, }
for i, tc := range testCases { result := searchMatrix(tc.matrix, tc.target) fmt.Printf("Test Case %d, Input: matrix = %v, target = %d\n", i+1, tc.matrix, tc.target) if result == tc.expected { fmt.Printf("Test Case %d, Output: %v, PASS\n", i+1, result) } else { fmt.Printf("Test Case %d, Output: %v, FAIL (Expected: %v)\n", i+1, result, tc.expected) } } }
|