73. Set Matrix Zeroes

Leetcode题解(24)-LMLPHP

分析:如果没有空间限制,这道题就很简单,但是要求空间复杂度为O(1),因此需要一些技巧。代码如下(copy网上的代码)

class Solution {
public:
void setZeroes(vector<vector<int> > &matrix)
{
bool bColZero = false, bRowZero = false; if (matrix.size() == || matrix[].size() == )
{
return;
} // Mark bColZero true when col[0] contains zero.
for (size_t row = ; row < matrix.size(); ++row)
{
if (!matrix[row][]) bColZero = true;
} // Mark bRowZero true when row[0] contains zero.
for (size_t col = ; col < matrix[].size(); ++col)
{
if (!matrix[][col]) bRowZero = true;
} // Map zero points to row[0] and col[0].
for (size_t row = ; row < matrix.size(); ++row)
{
for (size_t col = ; col < matrix[row].size(); ++col)
{
if (!matrix[row][col])
{
matrix[][col] = ;
matrix[row][] = ;
}
}
} // Set zero according to row[0] and col[0].
for (size_t row = ; row < matrix.size(); ++row)
{
for (size_t col = ; col < matrix[row].size(); ++col)
{
if (!matrix[row][] || !matrix[][col])
{
matrix[row][col] = ;
}
}
} // Process col[0].
if (bColZero)
{
for (size_t row = ; row < matrix.size(); ++row)
{
matrix[row][] = ;
}
} // Process row[0].
if (bRowZero)
{
for (size_t col = ; col < matrix[].size(); ++col)
{
matrix[][col] = ;
}
}
}
};

------------------------------------------------------------------------------分割线-------------------------------------------------------------------

74. Search a 2D Matrix

题目

Leetcode题解(24)-LMLPHP

分析,这道题目在《剑指offer》上出现过,思想是分段查找,只是查找的起点是右上角的元素,代码如下:

 class Solution {
public:
bool searchMatrix(vector<vector<int> > &matrix, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int i = , j = matrix[].size() - ; while (i < matrix.size() && j >= )
{
if (target == matrix[i][j])
return true;
else if (target < matrix[i][j])
j--;
else
i++;
} return false;
}
};

--------------------------------------------------------------------分割线------------------------------------------------------------------------------

75. Sort Colors

题目

Leetcode题解(24)-LMLPHP

分析:简单题目,可以直接统计0,1,2的个数,然后赋值即可

代码如下:

class Solution {
public:
void sortColors(vector<int>& nums) {
int size = nums.size();
int zero=,one=,two = ;
int i,j;
for(i=;i<size;i++)
{
if( == nums[i])
zero++;
else if( == nums[i])
one++;
else
two++;
}
i=;
j=;
for(j=;j<zero;j++)
nums[i++]=;
for(j=;j<one;j++)
nums[i++]=;
for(j=;j<two;j++)
nums[i++]=; }
};
05-11 19:47