第十一周

来源:互联网 发布:网络购买白兰地 编辑:程序博客网 时间:2024/04/27 18:27

575. Distribute Candies

Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the sister could gain.

给哥哥和妹妹分一堆有不同种类的糖果,在兄妹所得糖果数目一样的前提下,求妹妹最多能得到多少种糖果。

不同的数字表示不同的糖果,用map记录每种糖果出现的次数。注意,由于要对半分,妹妹所能得到的最大糖果种类不能超过总数的一般。
int distributeCandies(vector<int>& candies) {     int num = candies.size();         map<int,int> candyKinds;     for(int i =0;i<total;i++)     {         candyKinds[candies[i]]++;     }     int kind = candyKinds.size();     if(kind<=num/2)         return kind;     else         return num/2;}

572. Subtree of Another Tree

Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.

判断B树是否为A树子树。

  1. 前序遍历A树,若遇到节点与B树根节点相等,则调用判断俩树相等的函数equal。
  2. 若判断为false,则再分别调用函数自身判断左子树或右子树是否满足条件,只要一个成立,就返回true,否则返回false。
  bool equal(TreeNode* s, TreeNode* t)    {        if(s==NULL||t==NULL)            return (s==t);       if(s->val!=t->val)        return false;       if(!equal(s->left,t->left))        return false;       if(!equal(s->right,t->right))        return false;        return true;    }    bool isSubtree(TreeNode* s, TreeNode* t) {        if(s==NULL&&t==NULL)            return true;        else if(t==NULL)            return true;        bool equal1,equal2;        if(equal(s,t))         return true;        if(s->left==NULL)            equal1=false;        else            equal1=isSubtree(s->left,t);        if(s->right==NULL)            equal2=false;        else            equal2=isSubtree(s->right,t);        if (equal1||equal2)            return true;         else              return false;    }
0 0
原创粉丝点击