1.二维数组中的查找
/**************************************************************/
/* 题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。 */
/**************************************************************/
#include <iostream>
#include <vector>
using namespace std;
bool Find(int target, vector<vector<int> > array) {
if (array.empty())
return false;
int row = array.size();
int col = array[0].size();
int i = row-1, j = 0;
while (i >= 0&&j < col)
{
if (target == array[i][j])
return true;
else if (target > array[i][j])
j++;
else if (target < array[i][j])
i--;
}
return false;
}
int main()
{
int a[] = { 0,1,2 };
int b[] = { 3,4,5 };
int c[] = { 6,7,8 };
int num = 1;
vector<vector<int> > array;
vector<int> vec1(a, a + 3);
vector<int> vec2(b, b + 3);
vector<int> vec3(c, c + 3);
array.push_back(vec1);
array.push_back(vec2);
array.push_back(vec3);
bool res = Find(num, array);
cout << res << endl;
system("pause");
return 0;
}
2.替换空格
/*
题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。
例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
*/
#include <iostream>
#include <cstring>
using namespace std;
void replaceSpace(char *str, int length) {
int num = 0; //保存空格的个数
char *p = str;
while (*p != '\0')
{
if (*p==' ')
num++;
p++;
}
str[length + num * 2] = '\0';
int tmp = length - 1;
for (int i = tmp; i >= 0; i--)
{
if (str[i]!=' ')
{
str[i + num * 2] = str[i];
}
if (str[i] == ' ')
{
num--;
str[i + num * 2] = '%';
str[i + 1 + num * 2] = '2';
str[i + 2 + num * 2] = '0';
}
}
}
int main()
{
char c[1024] = "we are happy.";
replaceSpace(c, strlen(c));
for (int i = 0; i < strlen(c); i++)
{
cout << c[i];
}
cout << endl;
system("pause");
return 0;
}
3.从尾到头打印链表
/**************************************************************/
/* 题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。 */
/**************************************************************/
vector<int> printListFromTailToHead(ListNode* head) {
stack<int> stc;
while (head != NULL)
{
stc.push(head->val);
head = head->next;
}
vector<int> vec;
while (!stc.empty())
{
vec.push_back(stc.top());
stc.pop();
}
return vec;
}