The searchMatrix function searches for a given target value in a matrix. The matrix is a two-dimensional array in which the elements are sorted in row-wise order. The function returns true if the target value is found in the matrix, else false.
Code example:
bool searchMatrix(vector>& matrix, int target) { int rows = matrix.size(); if(rows == 0) return false; int cols = matrix[0].size(); int left = 0, right = rows * cols - 1; while(left <= right) { int mid = left + (right - left) / 2; int row = mid / cols; int col = mid % cols; if(matrix[row][col] == target) return true; else if(matrix[row][col] < target) left = mid + 1; else right = mid - 1; } return false; }
Example description:
We have an n x m matrix, which is represented by a two-dimensional array. Suppose matrix is the following matrix:
Now suppose the target value is 3. We can use the searchMatrix function to determine whether 3 is present in the matrix or not. In this example, the function will return true.
Package library:
The searchMatrix function is a part of the C++ Standard Template Library (STL). Hence, the package library for this function is .
C++ (Cpp) Solution::searchMatrix - 30 examples found. These are the top rated real world C++ (Cpp) examples of Solution::searchMatrix from package LeetCode extracted from open source projects. You can rate examples to help us improve the quality of examples.