Skip to content

Commit 2daa03d

Browse files
committed
search_a_2D_matrix
1 parent 97362bc commit 2daa03d

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
6363
#### [70. climbing stairs](https://github.com/hitzzc/go-leetcode/tree/master/climbing_stairs)
6464
#### [72. edit distance](https://github.com/hitzzc/go-leetcode/tree/master/edit_distance)
6565
#### [73. set matrix zeroes](https://github.com/hitzzc/go-leetcode/tree/master/set_matrix_zeroes)
66+
#### [74. search a 2D matrix](https://github.com/hitzzc/go-leetcode/tree/master/search_a_2D_matrix)
6667

6768

6869

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package search_a_2D_matrix
2+
3+
func searchMatrix(matrix [][]int, target int) bool {
4+
if len(matrix) == 0 || len(matrix[0]) == 0 {
5+
return false
6+
}
7+
row := -1
8+
for i := 0; i < len(matrix); i++ {
9+
if matrix[i][0] <= target && (i < len(matrix)-1 && matrix[i+1][0] > target || i == len(matrix)-1) {
10+
row = i
11+
break
12+
}
13+
}
14+
if row == -1 {
15+
return false
16+
}
17+
return binarySearch(matrix[row], 0, len(matrix[row])-1, target)
18+
}
19+
20+
func binarySearch(array []int, i, j, target int) bool {
21+
if i > j {
22+
return false
23+
}
24+
mid := i + (j-i)/2
25+
if array[mid] == target {
26+
return true
27+
}
28+
success := binarySearch(array, i, mid-1, target)
29+
if success {
30+
return true
31+
}
32+
return binarySearch(array, mid+1, j, target)
33+
}

0 commit comments

Comments
 (0)