题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
int row = (int)array.size();
int col = (int)array[0].size();
if (row == 0 || col == 0)
return false;
if (target < array[0][0] || target > array[row - 1][col - 1])
return false;
int i = 0;
int j = col - 1;
while (i < row && j >= 0)
{
if (array[i][j] > target)
{
j--;
}
else if (array[i][j] < target)
{
i++;
}
else
{
return 1;
}
}
return 0;
}
};
class Solution
{
public:
void replaceSpace(char *str,int length)
{
int spacenum = 0;
for(int i = 0; i<length; i++) //统计空格数
{
if(str[i] == ' ') spacenum++;
}
int newlength = length + spacenum*2; //新长度
int indexold = length - 1, indexnew = newlength - 1; //设置新旧两个指针
for(; indexold >= 0 && indexnew>indexold; indexold--) //indexold从后往前扫描整个字符串
{
if(str[indexold] == ' ') //将空格替换为“20%”
{
str[indexnew--] = '0';
str[indexnew--] = '2';
str[indexnew--] = '%';
}
else
str[indexnew--] = str[indexold];
}
}
};
题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> a;
ListNode *p;
p=head;
while(p!=NULL){
a.push_back(p->val);
p=p->next;
}
reverse(a.begin(),a.end());//反转
return a;
}
};
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
int result;
if(stack2.empty()){
while(!stack1.empty()){
stack2.push(stack1.top());
stack1.pop();
}
}
result = stack2.top();
stack2.pop();
return result;
}
private:
stack<int> stack1;
stack<int> stack2;
};