腾讯笔试:格林码+map

来源:互联网 发布:中山大学软件学院 编辑:程序博客网 时间:2024/06/12 01:30

在一组数的编码中,若任意两个相邻的代码只有一位二进制数不同, 则称这种编码为格雷码(Gray Code),请编写一个函数,使用递归的方法生成N位的格雷码。

给定一个整数n,请返回n位的格雷码,顺序为从0开始。

测试样例:
1

返回:["0","1"]

class GrayCode {public:    vector<string> getGray(int n) {        vector<string> vecstr,vecres;        vecstr.push_back("0");        vecstr.push_back("1");        if(n==1) return vecstr;        for (int k = 1; k < n; ++k)        {            vector<string> newvec;             for (int i = 0; i < vecstr.size(); ++i)            {                string newstr_0="0"+vecstr[i];                newvec.push_back(newstr_0);            }            for (int i = vecstr.size()-1; i >=0 ; --i)            {                string newstr_1="1"+vecstr[i];                newvec.push_back(newstr_1);            }            vecstr=newvec;            vecres=newvec;        }        return vecres;           }};

春节期间小明使用微信收到很多个红包,非常开心。在查看领取红包记录时发现,某个红包金额出现的次数超过了红包总数的一半。请帮小明找到该红包金额。写出具体算法思路和代码实现,要求算法尽可能高效。

给定一个红包的金额数组gifts及它的大小n,请返回所求红包的金额。

若没有金额超过总数的一半,返回0。
测试样例:
[1,2,3,2,2],5
返回:2
class Gift {public:    int getValue(vector<int> gifts, int n) {        map<int,int> mp;        for (int i = 0; i < n; ++i)        {            mp[gifts[i]]++;            if(mp[gifts[i]]>n/2) return gifts[i];        }        return 0;    }};




0 0
原创粉丝点击