二维数组中的查找
class Solution {
public:
bool Find(int target, vector<vector<int> > array)
{
if (array.size() <= 0 || array[0].size() <= 0)
return false;
int m = array.size() - 1;
int n = 0;
while(m >= 0 && n < array[0].size())
{
if (array[m][n] == target)
{
return true;
}
else if (array[m][n] > target)
{
m --;
}
else if (array[m][n] < target)
{
n ++;
}
}
return false;
}
};
替换空格
class Solution {
public:
void replaceSpace(char *str,int length)
{
if (str == NULL || length <= 0)
return;
int oldIndex = 0;
int newIndex = 0;
int blankNum = 0;
while(str[oldIndex] != '\0')
{
if (str[oldIndex] == ' ')
{
blankNum ++;
}
oldIndex ++;
}
newIndex = oldIndex + blankNum *2;
while(oldIndex >= 0 )
{
if (str[oldIndex] == ' ')
{
str[newIndex--] = '0';
str[newIndex--] = '2';
str[newIndex--] = '%';
}
else
{
str[newIndex--] = str[oldIndex];
}
oldIndex --;
}
}
};
从尾到头打印链表
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head)
{
vector<int> resualt;
stack<int> numStack;
while (head)
{
numStack.push(head->val);
head = head -> next;
}
while (numStack.size() > 0)
{
resualt.push_back(numStack.top());
numStack.pop();
}
return resualt;
}
};
重建二叉树
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin)
{
TreeNode* tree;
if (pre.size() <= 0)
{
tree = NULL;
}
else if (pre.size() == 1)
{
tree = new TreeNode(pre[0]);
}
else
{
vector<int> leftPre;
vector<int> leftVin;
vector<int> rightPre;
vector<int> rightVin;
bool didFind = false;
int currentIndex = 0;
while (currentIndex < vin.size())
{
if (vin[currentIndex] != pre[0])
{
if (!didFind)
{
leftVin.push_back(vin[currentIndex]);
}
else
{
rightVin.push_back(vin[currentIndex]);
}
}
else
{
didFind = true;
}
currentIndex ++;
}
for (int i = 1;i < pre.size();i ++)
{
if (i <= leftVin.size())
{
leftPre.push_back(pre[i]);
}
else
{
rightPre.push_back(pre[i]);
}
}
tree = new TreeNode(pre[0]);
tree -> left = reConstructBinaryTree(leftPre,leftVin);
tree -> right = reConstructBinaryTree(rightPre,rightVin);
}
return tree;
}
};
网友评论