class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
for (int i = 0; i < k-1; i++)
{
pop(matrix);
}
return matrix[0][0];
}
void swap(std::vector<std::vector<int>>& matrix, int i, int j, int ii, int jj)
{
int tmp = matrix[i][j];
matrix[i][j] = matrix[ii][jj];
matrix[ii][jj] = tmp;
}
void pop(std::vector<std::vector<int>>& matrix)
{
int n = matrix.size();
int i = 0;
int j = 0;
matrix[i][j] = INT_MAX;
while (i < n - 1 || j < n - 1)
{
int a = INT_MAX;
if (i < n - 1)
{
a = matrix[i + 1][j];
}
int b = INT_MAX;
if (j < n - 1)
{
b = matrix[i][j + 1];
}
if (a == b && a == INT_MAX)
{
break;
}
if (a < b)
{
swap(matrix, i, j, i + 1, j);
i++;
}
else
{
swap(matrix, i, j, i, j + 1);
j++;
}
}
}
};
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
for (int i = 0; i < k-1; i++)
{
pop(matrix);
}
return matrix[0][0];
}
void swap(std::vector<std::vector<int>>& matrix, int i, int j, int ii, int jj)
{
int tmp = matrix[i][j];
matrix[i][j] = matrix[ii][jj];
matrix[ii][jj] = tmp;
}
void pop(std::vector<std::vector<int>>& matrix)
{
int n = matrix.size();
int i = 0;
int j = 0;
matrix[i][j] = INT_MAX;
while (i < n - 1 || j < n - 1)
{
int a = INT_MAX;
if (i < n - 1)
{
a = matrix[i + 1][j];
}
int b = INT_MAX;
if (j < n - 1)
{
b = matrix[i][j + 1];
}
if (a == b && a == INT_MAX)
{
break;
}
if (a < b)
{
swap(matrix, i, j, i + 1, j);
i++;
}
else
{
swap(matrix, i, j, i, j + 1);
j++;
}
}
}
};
评论
发表评论