zoukankan      html  css  js  c++  java
  • [腾讯编程题]微信红包

    [编程题] 微信红包
    春节期间小明使用微信收到很多个红包,非常开心。在查看领取红包记录时发现,某个红包金额出现的次数超过了红包总数的一半。请帮小明找到该红包金额。写出具体算法思路和代码实现,要求算法尽可能高效。
    给定一个红包的金额数组gifts及它的大小n,请返回所求红包的金额。
    若没有金额超过总数的一半,返回0。
    测试样例:
    [1,2,3,2,2],5
    返回:2

    class Gift {
    public:
        int getValue(vector<int> gifts, int n) {
            // write code here
            int cnt=0;
            int val;
            for(int i=0;i<n;i++)
            {
                if(cnt==0)
                {
                    val=gifts[i];
                    cnt=1;
                    continue;
                }
                if(val==gifts[i])
                {
                    cnt++;
                }
                else
                {
                    cnt--;
                }
            }
            cnt=0;
            for(int i=0;i<n;i++)
                if(gifts[i]==val) cnt++;
            if(cnt>n/2) return val;
            else return 0;
        }
    };
  • 相关阅读:
    团队冲刺--第二阶段(七)
    对搜狗输入法的评价
    团队冲刺--第二阶段(六)
    课堂练习-找水王
    基础
    基础
    基础
    基础
    基础
    基础
  • 原文地址:https://www.cnblogs.com/learning-c/p/5740621.html
Copyright © 2011-2022 走看看