剑指offer系列–1
1.复杂链表的复制:每个节点含一个数据项、一个指向下一节点的指针、一个随机指向的指针;
struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x) :
label(x), next(NULL), random(NULL) {
}
};
RandomListNode* Clone(RandomListNode* pHead)
{
if(NULL == pHead)
return NULL;
//Copy: A->A'->B->B'->C->C'->NULL
RandomListNode *curr = pHead, *node;
while(NULL != curr)
{
node = new RandomListNode(curr->label);
node->next = curr->next;
curr->next = node;
curr = node->next;
}
//Random
curr = pHead;
while(NULL != curr)
{
node = curr->next;
if(NULL != curr->random)
node->random = curr->random->next;
curr = node->next;
}
RandomListNode *ret = pHead->next;
//Split
curr = pHead;
while(NULL != curr->next)
{
node = curr->next;
curr->next = node->next;
curr = node;
}
return ret;
}
2.二叉搜索树转有序双向链表:递归
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
TreeNode* Convert(TreeNode* pRootOfTree)
{
if(NULL == pRootOfTree)
return NULL;
TreeNode *ret = NULL, *temp = NULL;
//has left_child
if(NULL != pRootOfTree->left)
{
ret = temp = Convert(pRootOfTree->left);
while(NULL != temp->right)
temp = temp->right;
temp->right = pRootOfTree;
pRootOfTree->left = temp;
}
//don't have left_child
else
{
ret = pRootOfTree;
}
//has right_child
if(NULL != pRootOfTree->right)
{
temp = Convert(pRootOfTree->right);
temp->left = pRootOfTree;
pRootOfTree->right = temp;
}
return ret;
}
3.连续子序列的最大和
int FindGreatestSumOfSubArray(vector<int> array) {
if(array.empty()) return 0;
int sum = array[0], tempsum = array[0];
for(int i = 1; i < array.size(); i++)
{
tempsum = (tempsum < 0) ? array[i] : tempsum + array[i];
sum = (tempsum > sum) ? tempsum : sum;
}
return sum;
}