bool searchMatrix(vector<vector<int>> &matrix, int target)
{
int n = matrix.size();
int m = matrix[0].size();
int row = 0, col = m - 1;
while (row < n && col >= 0)
{
if (matrix[row][col] == target)
return true;
else if (matrix[row][col] < target)
row++;
else
col--;
}
return false;
}
bool searchMatrix(vector<vector<int>> &mat, int target){
int n = mat.size();
int m = mat[0].size();
int low=0,high=n*m-1; //Simulate 2d as 1d array
while(low<=high){
int mid = (low+high)/2;
int r = mid/m;// Row index in 2d from 1d
int c = mid%m;// Column index in 2d from 1d
if(mat[r][c]==target) return true;
else if(mat[r][c]<target) low=mid+1;
else high=mid-1;
}
return false;
}
vector<vector<int>> zeroMatrix(vector<vector<int>> &matrix, int n, int m) {
// int row[n] = {0}; --> matrix[..][0]
// int col[m] = {0}; --> matrix[0][..]
int col0 = 1;
// step 1: Traverse the matrix and
// mark 1st row & col accordingly:
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] == 0) {
// mark i-th row:
matrix[i][0] = 0;
// mark j-th column:
if (j != 0)
matrix[0][j] = 0;
else
col0 = 0;
}
}
}
// Step 2: Mark with 0 from (1,1) to (n-1, m-1):
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
if (matrix[i][j] != 0) {
// check for col & row:
if (matrix[i][0] == 0 || matrix[0][j] == 0) {
matrix[i][j] = 0;
}
}
}
}
//step 3: Finally mark the 1st col & then 1st row:
if (matrix[0][0] == 0) {
for (int j = 0; j < m; j++) {
matrix[0][j] = 0;
}
}
if (col0 == 0) {
for (int i = 0; i < n; i++) {
matrix[i][0] = 0;
}
}
return matrix;
}
Traverse in a spiral manner from top→left→bottom→left→top→ and so on.
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
int i=0,j=0;
vector<int>spiral;
int top=0,bottom = m-1,right=n-1,left=0;
while(top<=bottom && left<=right){
for(int i=left;i<=right;i++)
spiral.push_back(matrix[top][i]);
top++;
for(int i=top;i<=bottom;i++)
spiral.push_back(matrix[i][right]);
right--;
if(top<=bottom){
for(int i=right;i>=left;i--)
spiral.push_back(matrix[bottom][i]);
bottom--;
}
if(left<=right){
for(int i=bottom;i>=top;i--)
spiral.push_back(matrix[i][left]);
left++;
}
}
return spiral;
}
Binary search on value range: for each mid, count how many elements are ≤ mid using upper_bound. If count is ≤ half, move right; otherwise move left. The goal is to find the smallest value that has more than half the elements ≤ it (the median).