注:代码均在牛客网上运行,结果均通过!
二维数组查找
题目描述
- 在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
- 选择最右上角的数值与给定的target进行比较,如若数值小则往下移,如若数值大则往左移即可。
C++代码展示
class Solution {
public:
bool Find(int target, vector<vector<int> > array)
{
int rows = array.size();
int cols = array[0].size()-1;
int row = 0;
while(row<rows && cols>=0)
{
if(target==array[row][cols])
{
return true;
}
else if(target>array[row][cols])
{
row++;
}
else
{
cols--;
}
}
return false;
}
};
空格替换
题目描述
- 请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
C++代码展示
class Solution {
public:
void replaceSpace(char *str,int length)
{
if(str==NULL)
{
return;
}
int lenSpace = 0;
int oldLength = 0;
for(int i = 0;i<length-1;i++)
{
if(str[i]==' ')
{
lenSpace++;
}
oldLength++;
}
int newLen = oldLength + lenSpace*2;
int first = oldLength-1;
int last = newLen-1;
while(first<=last && first>=0)
{
if(str[first]!=' ')
{
str[last--] = str[first];
}
else if(str[first]==' ')
{
str[last--] = '0';
str[last--] = '2';
str[last--] = '%';
}
first--;
}
}
};
从头到尾打印链表
题目描述
- 输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
- 压入一个栈中,栈的特点是先进后出,因此栈顶元素就是链表的表尾节点,依次弹出。
C++代码展示
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head)
{
vector<int>result;
if(head==NULL)
{
return result;
}
ListNode*p = head;
ListNode*q = head->next;
head->next = NULL;
ListNode *r = NULL;
while(q!=NULL)
{
r = q->next;
q->next = p;
p = q;
q = r;
}
head = p;
ListNode *ptemp = head;
while(ptemp!=NULL)
{
result.push_back(ptemp->val);
ptemp = ptemp->next;
}
return result;
}
};