Skip to content

Commit 4bdc16b

Browse files
Create 2D_sorted.go
closes #270
1 parent ac76f4b commit 4bdc16b

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

2D Arrays (Matrix)/2D_sorted.go

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
func searchMatrix(matrix [][]int, target int) bool {
2+
if len(matrix) == 0 || len(matrix[0]) == 0 {
3+
return false
4+
}
5+
6+
rows, cols := len(matrix), len(matrix[0])
7+
left, right := 0, rows*cols-1
8+
9+
for left <= right {
10+
mid := left + (right-left)/2
11+
// Convert the 1D index back to 2D coordinates
12+
row, col := mid/cols, mid%cols
13+
midValue := matrix[row][col]
14+
15+
if midValue == target {
16+
return true
17+
} else if midValue < target {
18+
left = mid + 1
19+
} else {
20+
right = mid - 1
21+
}
22+
}
23+
24+
return false
25+
}

0 commit comments

Comments
 (0)