二维数组的查找
二维数组的每一行和每一列都是有序的,对于给定数字,确定二维数组里是否存在此数字。通过与数组右上角的数字比较(或者左下角,每一行或每一列的最大值),减小矩阵范围。
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
if (array.empty())
return false;
int rows = array.size(), cols = array[0].size();
//if (target<array[0][0] || target>array[rows - 1][cols - 1])
// return false;
int currR = 0, currC = cols - 1;
while (currR<rows&&currC >= 0) {
if (target<array[currR][currC])
--currC;
else if (target == array[currR][currC])
return true;
else
++currR;
}
return false;
}
};
替换空格
顺序容器的插入。待插入位置往后移动所需要的空间,第一遍扫描整个字符串,求出需要空出多少字节。记两个指针,第一个指针指向插入后的尾部,第二个指针指向当前字符串尾部。倒序扫描字符串,插入字符。
class Solution {
public:
void replaceSpace(char *str, int length) {
if (length <= 0)
return;
int countSpace = 0;
for (int i = 0; i < length; ++i)
if (str[i] == ' ')
++countSpace;
if (countSpace == 0)
return;
int newLength = length + 2 * countSpace;
char *p1 = str + length, *p2 = str + newLength;
while (p1 >= str) {
if (*p1 == ' ') {
*p2-- = '0';
*p2-- = '2';
*p2 = '%';
}
else
*p2 = *p1;
--p1;
--p2;
}
}
};