zoukankan      html  css  js  c++  java
  • leetcode_654. Maximum Binary Tree

    https://leetcode.com/problems/maximum-binary-tree/

    给定数组A,假设A[i]为数组最大值,创建根节点将其值赋为A[i],然后递归地用A[0,i-1]创建左子树,用A[i+1,n]创建右子树。


    使用vector的assign函数,该函数的特性:

    Any elements held in the container before the call are destroyed and replaced by newly constructed elements (no assignments of elements take place).
    This causes an automatic reallocation of the allocated storage space if -and only if- the new vector size surpasses the current vector capacity.


    class Solution
    {
    public:
    
        TreeNode* constructMaximumBinaryTree(vector<int>& nums)
        {
            vector<int>::iterator maxiter,iter=nums.begin();
            int maxn=INT_MIN,len=nums.size();
            while(iter!=nums.end())
            {
                if(*iter>maxn)
                {
                    maxn=*iter;
                    maxiter=iter;
                }
                iter++;
            }
            vector<int> lnums,rnums;
            TreeNode *node = new TreeNode(maxn);
            if(maxiter!=nums.begin())
            {
                lnums.assign(nums.begin(),maxiter);
                node->left = constructMaximumBinaryTree(lnums);
            }
            if(maxiter!=nums.end()-1)
            {
                rnums.assign(maxiter+1,nums.end());
                node->right = constructMaximumBinaryTree(rnums);
            }
            return node;
        }
    };

     

    因为assign函数的特性是,每次给vector赋值都会自动销毁原先vector中的对象,虽然这里使用的是c++内置类型,但是多少还是会有开销。所以又写了一个不使用assign的版本。

    class Solution
    {
    public:
    
        TreeNode* constructMaximumBinaryTree(vector<int>& nums)
        {
            return buildTree(nums, 0, nums.size()-1);
        }
        TreeNode* buildTree(vector<int>& nums, int l, int r)
        {
            if(l > r)
                return NULL;
            if(l == r)
            {
                TreeNode* node = new TreeNode(nums[l]);
                return node;
            }
            int max_n = INT_MIN, max_index = l;
            for(int i=l; i<=r ; i++)
                if(nums[i]>max_n)
                {
                    max_n = nums[i];
                    max_index = i;
                }
            TreeNode* root = new TreeNode(max_n);
            root->left = buildTree(nums, l, max_index-1);
            root->right = buildTree(nums, max_index+1, r);
            return root;
        }
    };

  • 相关阅读:
    【转】京东抢购服务高并发实践
    【转】聊聊高并发系统之队列术
    深入研究Clang(八) Clang代码阅读之打log读流程1
    【转】保证分布式系统数据一致性的6种方案
    TextureView实现视频播放
    Spring之FactoryBean
    支付宝系统架构
    【转】高并发系统之限流特技
    Go语言中new和make的区别
    Linux下安装Beego:go install: cannot install cross-compiled binaries when GOBIN is set
  • 原文地址:https://www.cnblogs.com/jasonlixuetao/p/10582782.html
Copyright © 2011-2022 走看看