剑指offer系列--1

剑指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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值