Intermediate Level
Implement the searchSortedMatrix method that checks whether the target exists in a sorted matrix.
The input contains a sorted matrix, its rows and cols, and a target value.
Each row is sorted in ascending order, and the matrix can be searched like one sorted list when rows continue in increasing order.
Your task is to return true if the target exists in the matrix, otherwise return false.
Use binary search by treating the matrix as a flattened sorted array.
The virtual array has rows * cols positions. For any middle index, convert it back to matrix coordinates using row = mid / cols and col = mid % cols.
Compare the middle value with the target and move the search range just like normal binary search.
Pseudocode:
function searchSortedMatrix(matrix, rows, cols, target):
left = 0
right = rows * cols - 1
while left <= right:
mid = (left + right) / 2
row = mid / cols
col = mid % cols
value = matrix[row][col]
if value == target:
return true
else if value < target:
left = mid + 1
else:
right = mid - 1
return false