第十一週

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;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章